From b8e92cd7b2cfdb3a63e12e1769f0a3f0cd668393 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 05:47:24 -0500 Subject: [PATCH 01/21] feat(rust): build the docs view and write the model explorer without Node The Rust port builds the port-neutral docs view from its loaded model (metaobjects::docs_view), byte-identical to TypeScript on every fixtures/explorer-conformance case, and a new opt-in docs-site generator writes explorer.json, the explorer app, explorer-model.js and explorer-stamp.js. The app is a canonical copy in metaobjects-codegen (synced by scripts/sync-explorer-app.sh, held by the explorer app copies gate) and ships in the published crate. Rust codegen now records generatedBy/sourceNode provenance in the hash manifest per the shared provenance vector, and the engine runs a run-output reader (docs-site) after every other generator, so gen and verify list the same files. The docs-site builder is engine, as the shared registry rules: eject refuses it and gen --list marks it [package-only]; an owned theme in codegen/docs-site/ replaces the shipped one. metaobjects::meta_endpoint adds the framework-free /_meta and /_meta/docs bodies (ETag and If-None-Match as TypeScript's). --- changelog.d/explorer-rust.md | 23 + docs/features/docs-view.md | 6 +- docs/features/explorer-data.md | 10 +- docs/features/explorer-site.md | 21 +- docs/features/metadata-api.md | 43 +- docs/ports/rust.md | 62 +- .../.gen-state/.hashes/tasks.json | 24 +- explorer-app/README.md | 1 + fixtures/codegen-skip-conformance/README.md | 4 +- fixtures/explorer-conformance/README.md | 6 + .../registry.json | 4 +- scripts/ci-local.sh | 3 +- scripts/sync-explorer-app.sh | 1 + server/rust/metaobjects-cli/src/lib.rs | 7 +- server/rust/metaobjects-cli/tests/cli.rs | 16 +- .../explorer-app/assets/3d-force-graph.min.js | 1056 ++++++++++++ .../explorer-app/assets/cytoscape.min.js | 32 + .../explorer-app/assets/explorer-app.js | 269 ++++ .../explorer-app/assets/explorer.css | 238 +++ .../explorer-app/assets/explorer.js | 422 +++++ .../explorer-app/index.html | 20 + server/rust/metaobjects-codegen/src/client.rs | 7 +- .../rust/metaobjects-codegen/src/commands.rs | 7 +- .../rust/metaobjects-codegen/src/docs_site.rs | 458 ++++++ server/rust/metaobjects-codegen/src/eject.rs | 46 + server/rust/metaobjects-codegen/src/engine.rs | 91 +- server/rust/metaobjects-codegen/src/entity.rs | 7 +- .../rust/metaobjects-codegen/src/generator.rs | 30 +- server/rust/metaobjects-codegen/src/hashes.rs | 62 +- server/rust/metaobjects-codegen/src/lib.rs | 3 + .../metaobjects-codegen/src/output_parser.rs | 11 +- .../metaobjects-codegen/src/output_prompt.rs | 14 +- .../metaobjects-codegen/src/render_helper.rs | 11 +- .../metaobjects-codegen/src/repository.rs | 11 +- .../rust/metaobjects-codegen/src/service.rs | 11 +- .../metaobjects-codegen/src/service_routes.rs | 10 +- .../metaobjects-codegen/tests/common/mod.rs | 7 +- .../metaobjects-codegen/tests/docs_site.rs | 231 +++ .../metaobjects-codegen/tests/entity_edges.rs | 1 + .../tests/generator_registry.rs | 29 +- .../rust/metaobjects-codegen/tests/golden.rs | 2 + .../tests/hash_manifest.rs | 56 + .../tests/list_query_conformance.rs | 1 + .../tests/reference_nodes.rs | 1 + .../metaobjects-codegen/tests/rules_inert.rs | 17 + .../metaobjects-codegen/tests/run_engine.rs | 24 +- server/rust/metaobjects/src/docs_view.rs | 1431 +++++++++++++++++ server/rust/metaobjects/src/json.rs | 43 +- server/rust/metaobjects/src/lib.rs | 2 + server/rust/metaobjects/src/loader.rs | 53 +- server/rust/metaobjects/src/meta_endpoint.rs | 113 ++ server/rust/metaobjects/src/providers.rs | 17 +- .../tests/docs_view_conformance.rs | 119 ++ 53 files changed, 5081 insertions(+), 113 deletions(-) create mode 100644 changelog.d/explorer-rust.md create mode 100644 server/rust/metaobjects-codegen/explorer-app/assets/3d-force-graph.min.js create mode 100644 server/rust/metaobjects-codegen/explorer-app/assets/cytoscape.min.js create mode 100644 server/rust/metaobjects-codegen/explorer-app/assets/explorer-app.js create mode 100644 server/rust/metaobjects-codegen/explorer-app/assets/explorer.css create mode 100644 server/rust/metaobjects-codegen/explorer-app/assets/explorer.js create mode 100644 server/rust/metaobjects-codegen/explorer-app/index.html create mode 100644 server/rust/metaobjects-codegen/src/docs_site.rs create mode 100644 server/rust/metaobjects-codegen/tests/docs_site.rs create mode 100644 server/rust/metaobjects/src/docs_view.rs create mode 100644 server/rust/metaobjects/src/meta_endpoint.rs create mode 100644 server/rust/metaobjects/tests/docs_view_conformance.rs diff --git a/changelog.d/explorer-rust.md b/changelog.d/explorer-rust.md new file mode 100644 index 0000000000..ef1a3eee7c --- /dev/null +++ b/changelog.d/explorer-rust.md @@ -0,0 +1,23 @@ +- **Rust: the model explorer with no Node.** The Rust port builds the docs view from its loaded + model (`metaobjects::docs_view::build`), byte for byte what TypeScript builds for every + `fixtures/explorer-conformance/` case. A new opt-in `docs-site` generator writes + `explorer.json`, the explorer app, `explorer-model.js` and `explorer-stamp.js` under + `site/`. It reads prompt texts from the metadata directories, `templates/` and a `prompts` + directory, and takes `subDir`, `title`, `stamp`, `verifyFile` and `routesFile` as options. + Each node lists the files generated for it: this run's (the engine runs the site after every + other generator) and the committed manifest's outside the run, so `cargo meta verify` renders + what `gen` wrote. The site builder is engine, as in every port: `cargo meta eject docs-site` + refuses, `gen --list` marks it `[package-only]`, and an owned theme in `codegen/docs-site/` + replaces the shipped one. The app files are a canonical copy in the crate + (`metaobjects-codegen/explorer-app/`, held to the root `explorer-app/` by the + `explorer app copies` gate) and ship in the published package. The running application can serve + the same view at `{apiPrefix}/_meta/docs`: `metaobjects::meta_endpoint::docs` builds it once and + carries its ETag, and the host mounts it as it mounts `/_meta` (`meta_endpoint::meta_json`, + new in Rust too). + + Rust codegen now also records which node each generated file came from, `{ "hash", + "generatedBy", "sourceNode" }` in the hash manifest, held to the shared `provenance` vector in + `fixtures/codegen-skip-conformance/manifests.json`. A file rendered for no single node, such as + a shared `meta_*` crate's, keeps the plain hash. Upgrading: the next `cargo meta gen` rewrites + the committed `.metaobjects/.gen-state/.hashes/` files once. Commit them; generated source + files do not change. diff --git a/docs/features/docs-view.md b/docs/features/docs-view.md index dde6a53ae1..7f9c072834 100644 --- a/docs/features/docs-view.md +++ b/docs/features/docs-view.md @@ -13,11 +13,11 @@ writes the same bytes for the same model, and the shared corpus [`fixtures/explorer-conformance/`](../../fixtures/explorer-conformance/) holds them to that. TypeScript builds it today, and so do Java and Kotlin (one JVM builder, `DocsView` in -`metadata`). `buildDocsView` and `serializeDocsView` are exported from `@metaobjectsdev/metadata`, +`metadata`) and Rust (`metaobjects::docs_view`). `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)). C#, Python and Rust will build it as their own step of the same +[explorer-site.md](explorer-site.md)). C# and Python will build it as their own step of the same plan ([explorer-data.md](explorer-data.md#not-built-yet)). The explorer pages still render their -HTML in TypeScript; the JVM copies the app and writes the same `explorer.json`. +HTML in TypeScript; the JVM and Rust copy the app and write the same `explorer.json`. 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 diff --git a/docs/features/explorer-data.md b/docs/features/explorer-data.md index a653375d57..ba34ecce2d 100644 --- a/docs/features/explorer-data.md +++ b/docs/features/explorer-data.md @@ -119,10 +119,10 @@ manifest reader takes `hash` from either form. The provenance field is named `generatedBy`, not `generator`. In a Java or Kotlin module's manifest, `generator` means that generator owns the file (ADR-0060), and the orphan sweep acts on that ownership, so a JVM entry carries both: `{ "hash", "generator", "outputDir", -"generatedBy", "sourceNode" }`. The four ports that write provenance write the same entry for the +"generatedBy", "sourceNode" }`. The five ports that write provenance write the same entry for the same records; the shared vector `provenance` in [`fixtures/codegen-skip-conformance/manifests.json`](../../fixtures/codegen-skip-conformance/manifests.json) -holds TypeScript, C#, Java and Python to it. Kotlin and Rust write no provenance yet. +holds TypeScript, C#, Java, Python and Rust to it. Kotlin writes no provenance yet. ## Building it by hand @@ -156,9 +156,9 @@ malformed leaves its part of the view empty. - **`usage`**: which hand-written modules import a generated module. The design marks it optional, and nothing builds it yet. -- **Provenance from the Kotlin and Rust generators.** Their manifest entries have no - `sourceNode` yet, so for those ports a node lists no files. -- **The docs view in C#, Python and Rust.** TypeScript, Java and Kotlin build it today; the +- **Provenance from the Kotlin generators.** Their manifest entries have no + `sourceNode` yet, so for that port a node lists no files. +- **The docs view in C# and Python.** TypeScript, Java, Kotlin and Rust build it today; the corpus is what the other ports will be held to. ## Verified by diff --git a/docs/features/explorer-site.md b/docs/features/explorer-site.md index 48c4990f82..e0f83b0831 100644 --- a/docs/features/explorer-site.md +++ b/docs/features/explorer-site.md @@ -73,7 +73,8 @@ same model and inputs: every port that builds the docs view is held to | TypeScript | `docsSiteFile()` (`meta gen`) | `output: "app"` (default) or `"static"`; `site: "classic"` for the earlier site | The model, the requirement ledger, the files and routes this run wrote and mounts | | Java | `com.metaobjects.generator.DocsSiteGenerator` (`mvn metaobjects:generate`), no Node | The app only | The model, the files generated per node (this execution's, and what the committed hash manifest records for the module's other executions), and a `verify --format json` payload when you name one (`verifyFile`) | | Kotlin | the same JVM `DocsSiteGenerator`, through `codegen-kotlin`'s registry | The app only | As Java; the Kotlin generators do not record provenance in the manifest yet, so their files are not listed | -| C#, Python, Rust | not yet | | | +| C#, Python | not yet | | | +| Rust | `docs-site` (`cargo meta gen`, `metaobjects_codegen::DocsSiteGenerator`), no Node | The app only | The model, the files generated per node (this run's, and what the committed hash manifest records outside the directories the run clears), and a `verify --format json` payload (`verifyFile`) and a routes file (`routesFile`) when you name them. Options and the owned theme: [the Rust port](../ports/rust.md#docs-site-the-model-explorer) | On the JVM, wire it like any other generator, with its own output directory: @@ -297,16 +298,17 @@ a dangling link. `createExplorer` (the page table both outputs draw from) and - An LLM-written summary, a test-result overlay, zoom levels and lenses on the map, and publishing the site. -- The docs view route in C#, Python and Rust: the contract is in +- The docs view route in C# and Python: the contract is in [metadata-api.md](metadata-api.md#the-docs-view-endpoint-get-_metadocs), and each port serves - it once it has its docs view builder. Java and Kotlin ship it (`MetaEndpoint.docs(root)`). -- The app in C#, Python and Rust: its files are in each port's package already (see + it once it has its docs view builder. Java and Kotlin ship it (`MetaEndpoint.docs(root)`), and + Rust (`metaobjects::meta_endpoint::docs`). +- The app in C# and Python: its files are in each port's package already (see `explorer-app/README.md`), and each port's docs-site generator is still to write them. - The static export and the classic site outside TypeScript. - "Hand-written code that imports it": the site reads no import graph, so the object pages say it was not scanned. -- Generated-file provenance from the Kotlin and Rust generators (see - [explorer-data.md](explorer-data.md)), so for those ports the generated-file lists are empty. +- Generated-file provenance from the Kotlin generators (see + [explorer-data.md](explorer-data.md)), so for that port the generated-file lists are empty. ## Verified by @@ -317,6 +319,13 @@ a dangling link. `createExplorer` (the page table both outputs draw from) and stamp, an owned theme wins, and the generator lists the manifest's files. - `server/java/metadata/src/test/java/com/metaobjects/io/json/MetaDocsEndpointTest.java`: the JVM docs view route body is the `model-alone` view, and its ETag is TypeScript's. +- `server/rust/metaobjects/tests/docs_view_conformance.rs`: the Rust docs view builder writes + every `fixtures/explorer-conformance/` case byte for byte, and the `/_meta/docs` body is the + `model-alone` view with TypeScript's ETag. +- `server/rust/metaobjects-codegen/tests/docs_site.rs`: the Rust site's app files are the + canonical copy, its model script has TypeScript's bytes and stamp, an owned theme wins, prompt + texts are read only inside the prompt directories, and a `cargo meta gen` run writes the shop + case's `explorer.json` over the manifest's files and verifies clean. - `server/typescript/packages/docs-site/test/explorer-app.test.ts`: the files the app output writes, the model and stamp files, owned templates and theme, and the committed bundle, run outside a browser, drawing every page the static export writes byte for byte on the shop, crm diff --git a/docs/features/metadata-api.md b/docs/features/metadata-api.md index fd4d35ca69..ed71d41aea 100644 --- a/docs/features/metadata-api.md +++ b/docs/features/metadata-api.md @@ -63,12 +63,13 @@ the package, including consumers with no HTTP surface at all. | Java (`metaobjects-metadata`) | `com.metaobjects.io.json.MetaEndpoint.META_ROUTE_PATH`, `MetaEndpoint.metaJson(MetaData root)` | Host mounts — `core-spring` carries `spring-context` but no `spring-web` | | Kotlin | consumes the Java `MetaEndpoint` symbol directly via the `metadata-ktx` facade — there is no separate Kotlin implementation | Host mounts | | Python (`metaobjects`) | `META_ROUTE_PATH`, `meta_json(root)` (both exported from the package root) | Host mounts — neither `metaobjects.runtime` nor `metaobjects.codegen.runtime` imports a web framework | +| Rust (`metaobjects`) | `metaobjects::meta_endpoint::META_ROUTE_PATH`, `meta_endpoint::meta_json(&tree, root)` | Host mounts — the `metaobjects` crate depends on no web framework | The response body is not a new thing to gate: each helper is a thin wrapper over that port's already-conformance-gated effective serializer (`canonicalSerializeEffective` / `SerializerJson.CanonicalSerializeEffective` / `CanonicalJsonSerializer.canonicalSerializeEffective` / -`canonical_serialize_effective`), so `/_meta`'s bytes ride on the existing +`canonical_serialize_effective`, in Python and in Rust), so `/_meta`'s bytes ride on the existing metadata conformance corpus rather than a new one built for this endpoint. The exact `content-type` header value is a per-port detail, not a pinned cross-port byte — TypeScript's mounts emit @@ -153,6 +154,20 @@ def meta() -> Response: return Response(meta_json(root), media_type="application/json") ``` +### Rust — axum + +```rust +use axum::{Router, routing::get}; +use metaobjects::meta_endpoint::{META_ROUTE_PATH, meta_json}; + +// tree, root: the model this app loaded. Serialized once: the model does not change after load. +let body = meta_json(&tree, root); +let app = Router::new().route( + &format!("/api{META_ROUTE_PATH}"), + get(move || async move { ([("content-type", "application/json")], body) }), +); +``` + ## Exposure Mounting `/_meta` is **opt-in** in every port — nothing registers it @@ -258,7 +273,31 @@ Kotlin calls the same symbols through `metadata-ktx`. To let the explorer read t `file://`, add `Access-Control-Allow-Origin: null` and `Access-Control-Expose-Headers: ETag` to that response, or use Spring's CORS configuration. -C#, Python and Rust serve the route once each has its docs view builder, with the +Rust ships the same helper in `metaobjects::meta_endpoint`, framework-free, and leaves the mount +to the host under the same guard: `docs(&tree, root, routes)` builds the view once and gives +`body`, `etag` and `matches(if_none_match)` (`META_DOCS_ROUTE_PATH`, +`meta_docs_json(&tree, root, routes)`, `meta_docs_etag`). With axum: + +```rust +use axum::{http::{HeaderMap, StatusCode, header}, response::IntoResponse, routing::get}; +use metaobjects::meta_endpoint::{META_DOCS_ROUTE_PATH, docs}; + +let docs = std::sync::Arc::new(docs(&tree, root, None)); +let app = app.route( + &format!("/api{META_DOCS_ROUTE_PATH}"), + get(move |headers: HeaderMap| async move { + let tag = headers.get(header::IF_NONE_MATCH).and_then(|v| v.to_str().ok()); + let common = [(header::ETAG, docs.etag.clone()), (header::CACHE_CONTROL, "no-cache".into())]; + if docs.matches(tag) { + (StatusCode::NOT_MODIFIED, common).into_response() + } else { + (common, [(header::CONTENT_TYPE, "application/json")], docs.body.clone()).into_response() + } + }), +); +``` + +C# and Python serve the route once each has its docs view builder, with the body that builder writes; their `/_meta` sections above show where each mounts it. ## Browser consumption diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 40a94feb12..b4aeb48501 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -35,7 +35,9 @@ The loader is the `metaobjects` crate, and the workspace at `server/rust/` adds | Frozen tree | The loader freezes the tree when it finishes. A frozen tree memoizes its resolved reads (effective children, attributes and array-ness), so many readers can share one. | | Timings | Every load records how long each phase and each validation pass took (`LoadResult::timings`). | | Report shapes | `metaobjects::report_shape::report_shape` derives an `object.report`'s fields (FR-044 Table B, with Table C's `required`): each dimension and measure, its subtype, and the `@of` field it takes its type from. It byte-matches `fixtures/persistence-conformance/report-shapes.json`, as every port does. | -| Code generation (`cargo meta`) | The run engine, twelve generators (`entity`, `rules-names`, `contract-types`, `repository`, `service`, `service-routes`, `client`, `commands`, `render-helper`, `output-parser`, `output-prompt`, and the opt-in `metamodel-docs`, the metamodel reference pages rendered from the shared Mustache set), the codegen and template drift gates and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | +| Docs view | `metaobjects::docs_view::build` builds the port-neutral docs view (`docs/features/docs-view.md`) from the loaded model, with the requirement ledger, the generated files and the routes when it is given them. It byte-matches `fixtures/explorer-conformance/`, as every port does. | +| Metadata routes | `metaobjects::meta_endpoint` holds the bodies of `GET /_meta` (`meta_json`) and `GET /_meta/docs` (`docs`, with its ETag and the `If-None-Match` check), framework-free, for the host to mount ([Metadata API](../features/metadata-api.md#rust--axum)). | +| Code generation (`cargo meta`) | The run engine, thirteen generators (`entity`, `rules-names`, `contract-types`, `repository`, `service`, `service-routes`, `client`, `commands`, `render-helper`, `output-parser`, `output-prompt`, and two opt-in docs generators: `metamodel-docs`, the metamodel reference pages rendered from the shared Mustache set, and `docs-site`, the model explorer), the codegen and template drift gates and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | ## The command: `cargo meta` @@ -78,15 +80,17 @@ one, and no eject is needed: The file takes that one key: a layer is only a generator, so there are no layer settings. An entry is a name, or `{"name": "", "options": {...}}` for a generator that takes options; the generator's `configure` reads them and refuses a key it does not know (`ERR_UNKNOWN_GENERATOR_OPTION`, -naming the options it takes). Of the shipped generators only `metamodel-docs` takes one (`subDir`), so +naming the options it takes). Of the shipped generators only the two docs generators take options +(`metamodel-docs` takes `subDir`; `docs-site` takes the six in [its section](#docs-site-the-model-explorer)), so any other option fails the run, also a run `--generators` narrows to other generators. A project with -no such file runs every generator but `service-routes` and `metamodel-docs`, which run only when they -are listed: an HTTP server is a choice the project makes, not a default, and so are the metamodel -reference pages. A generator that leaves the list has its files removed +no such file runs every generator but `service-routes`, `metamodel-docs` and `docs-site`, which run +only when they are listed: an HTTP server is a choice the project makes, not a default, and so are +the metamodel reference pages and the model explorer. A generator that leaves the list has its files removed on the next `gen` (a file somebody edited is refused by name instead), and the run fails, naming the file, for a name nothing offers, a duplicate, an unknown key, or a generator listed without one it builds on (`client`, `render-helper` and `output-parser` need `entity`; `commands` needs `entity` and `client`; each layer needs the one beneath it, up to `service-routes`, which needs `service`). `cargo meta gen --list` shows each generator -as `[configured]` or `[not configured]`, marks the opt-in one `[opt-in]`, and `--generators` narrows one run to some of the list. +as `[configured]` or `[not configured]`, marks the opt-in ones `[opt-in]` and the one that cannot be +ejected `[package-only]`, and `--generators` narrows one run to some of the list. **Exit codes** are the ones every port's tool uses: 0 success, 1 the run failed (a model that does not load, a refused file, drift), 2 a usage error. An unknown flag names the flags the command takes. @@ -482,6 +486,49 @@ An entity whose source has a read-only view beside its table (`source.rdb @kind: role) is written to the table and read back through the view, so the fields that view derives (`origin.*`) are in every answer, a write's included. +### `docs-site`: the model explorer + +The model explorer ([Explorer site](../features/explorer-site.md)), written with no Node: the +generator builds the docs view from the model this run loaded, and writes it with the explorer app +under `site/` in the output directory: + +```text +generated/site/ + index.html, assets/ the app: the same bytes in every port (the repository's explorer-app/) + explorer.json the docs view, byte for byte what every port writes for the model + explorer-model.js the docs view, the prompt texts, the title and the footer, as one script + explorer-stamp.js the model's hash, which the open app polls to reload itself +``` + +List it with its options: + +```json +{ "generators": ["entity", "client", { "name": "docs-site", "options": { "prompts": "prompts" } }] } +``` + +| Option | Default | What it does | +|---|---|---| +| `subDir` | `site` | The directory under the output it writes to; `""` writes at the output root | +| `title` | the project directory's name | The header and the home page title | +| `stamp` | none | Footer text, such as a version; none keeps the site a function of the model alone | +| `prompts` | none | A directory, relative to the project, of prompt `.mustache` sources outside the metadata directories and `templates/` (those two are always searched) | +| `verifyFile` | none | A `verify --format json` payload whose requirement rows the explorer shows. `cargo meta verify` has no requirement gate, so write it with another port's `verify` | +| `routesFile` | none | The routes the application mounts, `[{ node, method, path }]` with `node` a resolution key | + +Each node's page lists the files generated for it, read from the provenance the generators record +in the hash manifest (`generatedBy` and `sourceNode` on each file written for one node; a shared +crate's files stay a plain hash): the files this run wrote, and what the +committed manifest records outside the directories the run clears. The engine runs the generator +after every other one, so `cargo meta verify` renders the same lists the write run wrote. + +The site builder is engine, not a reference generator: `cargo meta eject docs-site` refuses, and +`gen --list` marks it `[package-only]`. What a project owns is the theme. Files in +`codegen/docs-site/` replace the shipped ones: `assets/explorer.css`, `assets/explorer.js`, and +`templates/explorer-*.mustache`, which the app uses in place of its own. Editing one regenerates. + +To read the docs view from the running application instead, mount `GET /_meta/docs` +([Metadata API](../features/metadata-api.md#rust--axum)) and open `index.html?source=`. + ### Owning a generator A generator is a reference helper @@ -607,7 +654,8 @@ regeneration, peak memory), so a port's speed can be tracked per feature next to ## What does not exist yet -- **Other generators.** There is no documentation generator. Projections and reports get no route, +- **Other generators.** The documentation generators are `metamodel-docs` and `docs-site`: there is no + per-entity reference page generator (`docs`, `api-docs`) and no static export of the explorer. Projections and reports get no route, client or commands yet, and a template over a sourceless `object.projection` payload gets no render function. - **The rest of the API-contract corpus.** The transport passes `core`, `write-through`, diff --git a/examples/rust-service/.metaobjects/.gen-state/.hashes/tasks.json b/examples/rust-service/.metaobjects/.gen-state/.hashes/tasks.json index 23a05f894a..7b07dd9322 100644 --- a/examples/rust-service/.metaobjects/.gen-state/.hashes/tasks.json +++ b/examples/rust-service/.metaobjects/.gen-state/.hashes/tasks.json @@ -1,6 +1,22 @@ { - "generated/tasks/src/task.rs": "c9494e046f1d9ec89cd5441247211303e2b26191bc4eed85f78f415b50a2b2e9", - "generated/tasks_http/src/task.rs": "f2c1bebac5452927c39a0c74c22e67ec2da699d5845d7e9bcccb6316f084b32e", - "generated/tasks_service/src/task.rs": "11fba25fd503ae858bcf6e3395c95b30ebcca1e4444dc4cfba1926c7fc8cfd11", - "generated/tasks_store/src/task.rs": "ae56db0385964c1f68b676bb0e29c3c10c5339cbfd3165e239b10a635fef5bda" + "generated/tasks/src/task.rs": { + "hash": "c9494e046f1d9ec89cd5441247211303e2b26191bc4eed85f78f415b50a2b2e9", + "generatedBy": "entity", + "sourceNode": "tasks::Task" + }, + "generated/tasks_http/src/task.rs": { + "hash": "f2c1bebac5452927c39a0c74c22e67ec2da699d5845d7e9bcccb6316f084b32e", + "generatedBy": "service-routes", + "sourceNode": "tasks::Task" + }, + "generated/tasks_service/src/task.rs": { + "hash": "11fba25fd503ae858bcf6e3395c95b30ebcca1e4444dc4cfba1926c7fc8cfd11", + "generatedBy": "service", + "sourceNode": "tasks::Task" + }, + "generated/tasks_store/src/task.rs": { + "hash": "ae56db0385964c1f68b676bb0e29c3c10c5339cbfd3165e239b10a635fef5bda", + "generatedBy": "repository", + "sourceNode": "tasks::Task" + } } diff --git a/explorer-app/README.md b/explorer-app/README.md index 41d6f759a3..6a593fdf88 100644 --- a/explorer-app/README.md +++ b/explorer-app/README.md @@ -40,6 +40,7 @@ Bun stops with an error that names the required version. | Python | `server/python/src/metaobjects/documentation/explorer_app/` | | Java and Kotlin | `server/java/codegen-base/src/main/resources/metaobjects/explorer-app/` | | C# | `server/csharp/MetaObjects.Codegen/ExplorerApp/` | +| Rust | `server/rust/metaobjects-codegen/explorer-app/` (compiled into the crate with `include_str!`, so it ships in the published package) | ## What a port writes beside the app diff --git a/fixtures/codegen-skip-conformance/README.md b/fixtures/codegen-skip-conformance/README.md index 40bec46c92..01232f36bd 100644 --- a/fixtures/codegen-skip-conformance/README.md +++ b/fixtures/codegen-skip-conformance/README.md @@ -43,8 +43,8 @@ vectors in `manifests.json` are run by each port's manifest unit tests, beside t as the loaded model, and the directory must hold exactly `afterFiles` (`goldenText` is one file's bytes in full). A record with a `sourceNode` makes the entry `{ "hash", , "generatedBy", "sourceNode" }`; one without returns it to the plain hash; a path with no recorded - hash is left out. Recording the same records again changes no file. TypeScript, C#, Java and - Python run it. + hash is left out. Recording the same records again changes no file. TypeScript, C#, Java, + Python and Rust run it (Rust in `server/rust/metaobjects-codegen/tests/hash_manifest.rs`). A port's tests also assert what the vectors cannot: two writes that change entries in two packages change two files and no third, a save that changes nothing writes nothing, a package that loses its diff --git a/fixtures/explorer-conformance/README.md b/fixtures/explorer-conformance/README.md index 150e0578f4..68edb523bc 100644 --- a/fixtures/explorer-conformance/README.md +++ b/fixtures/explorer-conformance/README.md @@ -110,3 +110,9 @@ Then review the diff: every changed line is a change to what a docs page can sho `hashes.json` as the gen-state manifest. - `server/java/metadata/src/test/java/com/metaobjects/io/json/MetaDocsEndpointTest.java`: the JVM docs view route body is `model-alone/expected.json`. +- `server/rust/metaobjects/tests/docs_view_conformance.rs`: the Rust builder reproduces every + case (it applies `provider.json` the same way), and the `/_meta/docs` body + (`metaobjects::meta_endpoint`) is `model-alone/expected.json`. +- `server/rust/metaobjects-codegen/tests/docs_site.rs`: the Rust `docs-site` generator writes + the shop case's `explorer.json` in a `cargo meta gen` run, reading `hashes.json` as the + gen-state manifest and `prompts/` for the prompt text. diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index a6d513edba..6d0bf84d9d 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -357,12 +357,12 @@ "concept": "The browsable HTML site of the model: navigation, search, a page per package and per object, ER diagrams.", "tier": "neutral", "layer": "docs", - "note": "It was `meta docs --site` until 1.1.0 (ADR-0034 Amendment 9). Java and Kotlin write the model explorer app over the docs view, with no Node (both run the JVM DocsSiteGenerator); the classic site and the page-per-screen static export stay TypeScript's.", + "note": "It was `meta docs --site` until 1.1.0 (ADR-0034 Amendment 9). Java, Kotlin and Rust write the model explorer app over the docs view, with no Node (Java and Kotlin the JVM DocsSiteGenerator, Rust its docs-site generator); the classic site and the page-per-screen static export stay TypeScript's.", "eject": { "exempt": "The site builder is engine: it assembles the page data the site's templates read, and what an adopter changes is those templates and the assets beside them, which `meta eject docs-site` copies into codegen/docs-site/ and the generator reads from there.", "ruling": "ADR-0034 Amendment 9 (restating Amendment 8, ruling 3)" }, - "ports": ["typescript", "java", "kotlin"] + "ports": ["typescript", "java", "kotlin", "rust"] }, "plantuml": { "concept": "PlantUML class diagram of the object model.", diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 9cbba46275..84a880812c 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -1138,7 +1138,8 @@ gate_explorer_app_drift() { server/typescript/packages/docs-site/app \ server/python/src/metaobjects/documentation/explorer_app \ server/java/codegen-base/src/main/resources/metaobjects/explorer-app \ - server/csharp/MetaObjects.Codegen/ExplorerApp; do + server/csharp/MetaObjects.Codegen/ExplorerApp \ + server/rust/metaobjects-codegen/explorer-app; do diff -r -x README.md explorer-app "$copy" || { echo " stale copy: $copy (run scripts/sync-explorer-app.sh)"; rc=1; } done return $rc diff --git a/scripts/sync-explorer-app.sh b/scripts/sync-explorer-app.sh index b2891126fa..c2721210a0 100755 --- a/scripts/sync-explorer-app.sh +++ b/scripts/sync-explorer-app.sh @@ -14,6 +14,7 @@ dests=( "$root/server/python/src/metaobjects/documentation/explorer_app" "$root/server/java/codegen-base/src/main/resources/metaobjects/explorer-app" "$root/server/csharp/MetaObjects.Codegen/ExplorerApp" + "$root/server/rust/metaobjects-codegen/explorer-app" ) for dst in "${dests[@]}"; do mkdir -p "$dst" diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 4e2570de5e..7f6a47de85 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -424,9 +424,14 @@ fn list_generators( Some(c) => format!(" [owned: {}]", c.state), None => String::new(), }; + let package_only = if r.package_only { + " [package-only]" + } else { + "" + }; let _ = writeln!( out, - "{} - {} (layer: {}){}{state}", + "{} - {} (layer: {}){}{package_only}{state}", r.name, r.summary, r.layer, diff --git a/server/rust/metaobjects-cli/tests/cli.rs b/server/rust/metaobjects-cli/tests/cli.rs index acdd2cfe2f..2293061043 100644 --- a/server/rust/metaobjects-cli/tests/cli.rs +++ b/server/rust/metaobjects-cli/tests/cli.rs @@ -278,7 +278,11 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl "{out}" ); assert_eq!(out.matches("[configured]").count(), 10, "{out}"); - assert_eq!(out.matches("[not configured]").count(), 2, "{out}"); + assert_eq!(out.matches("[not configured]").count(), 3, "{out}"); + assert!( + out.contains("(layer: docs) [not configured] [package-only]"), + "docs-site is listed as package-only: {out}" + ); // An edited list is never overwritten by a second init. p.write( "metaobjects.config.json", @@ -291,7 +295,7 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl ); let out = ok(&p.run(&["meta", "gen", "--list"])); assert!(out.contains("runs: entity\n"), "{out}"); - assert_eq!(out.matches("[not configured]").count(), 11, "{out}"); + assert_eq!(out.matches("[not configured]").count(), 12, "{out}"); } #[test] @@ -603,6 +607,14 @@ fn eject_copies_the_generator_never_overwrites_and_undo_takes_back_only_identica !p.exists("codegen"), "every name is checked before anything is written" ); + let r = p.run(&["meta", "eject", "docs-site"]); + assert_eq!(r.status.code(), Some(2)); + assert!( + text(&r.stderr).contains("docs-site stays in the package and has no copy to eject") + && text(&r.stderr).contains("codegen/docs-site/"), + "{}", + text(&r.stderr) + ); let out = ok(&p.run(&["meta", "eject", "entity"])); assert!( diff --git a/server/rust/metaobjects-codegen/explorer-app/assets/3d-force-graph.min.js b/server/rust/metaobjects-codegen/explorer-app/assets/3d-force-graph.min.js new file mode 100644 index 0000000000..3903a12250 --- /dev/null +++ b/server/rust/metaobjects-codegen/explorer-app/assets/3d-force-graph.min.js @@ -0,0 +1,1056 @@ +/*! + * 3d-force-graph 1.77.0, https://github.com/vasturiano/3d-force-graph, vendored unchanged from the + * npm package (dist/3d-force-graph.min.js) below this notice. MIT License. + * + * The build bundles these packages. Each licence follows; DOMPurify is offered under + * MPL-2.0 OR Apache-2.0 and is used here under Apache-2.0. + * + * 3d-force-graph (MIT) + * @babel/runtime (MIT) + * @tweenjs/tween.js (MIT) + * accessor-fn (MIT) + * d3-array (ISC) + * d3-binarytree (MIT) + * d3-color (ISC) + * d3-dispatch (ISC) + * d3-force-3d (MIT) + * d3-format (ISC) + * d3-interpolate (ISC) + * d3-octree (MIT) + * d3-quadtree (ISC) + * d3-scale (ISC) + * d3-scale-chromatic (ISC) + * d3-selection (ISC) + * d3-time (ISC) + * d3-time-format (ISC) + * d3-timer (ISC) + * data-bind-mapper (MIT) + * dompurify ((MPL-2.0 OR Apache-2.0)) + * float-tooltip (MIT) + * internmap (ISC) + * kapsule (MIT) + * lodash-es (MIT) + * ngraph.events (BSD-3-Clause) + * ngraph.forcelayout (BSD-3-Clause) + * ngraph.graph (BSD-3-Clause) + * ngraph.merge (MIT) + * ngraph.random (BSD-3-Clause) + * polished (MIT) + * preact (MIT) + * three (MIT) + * three-forcegraph (MIT) + * three-render-objects (MIT) + * tinycolor2 (MIT) + * + * ---- 3d-force-graph (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- @babel/runtime (MIT) ---- + * + * MIT License + * + * Copyright (c) 2014-present Sebastian McKenzie and other contributors + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * ---- @tweenjs/tween.js (MIT) ---- + * + * The MIT License + * + * Copyright (c) 2010-2012 Tween.js authors. + * + * Easing equations Copyright (c) 2001 Robert Penner http://robertpenner.com/easing/ + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * ---- accessor-fn (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- d3-array (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-binarytree (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- d3-color (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-dispatch (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-force-3d (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- d3-format (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-interpolate (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-octree (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- d3-quadtree (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-scale (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-scale-chromatic (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * Apache-Style Software License for ColorBrewer software and ColorBrewer Color Schemes + * + * Copyright 2002 Cynthia Brewer, Mark Harrower, and The Pennsylvania State University + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy of the + * License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * ---- d3-selection (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-time (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-time-format (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- d3-timer (ISC) ---- + * + * Copyright 2010-2026 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- data-bind-mapper (MIT) ---- + * + * MIT License + * + * Copyright (c) 2024 Vasco Asturiano + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- dompurify ((MPL-2.0 OR Apache-2.0)) ---- + * + * Apache License + * Version 2.0, January 2004 + * http://www.apache.org/licenses/ + * + * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + * + * 1. Definitions. + * + * "License" shall mean the terms and conditions for use, reproduction, + * and distribution as defined by Sections 1 through 9 of this document. + * + * "Licensor" shall mean the copyright owner or entity authorized by + * the copyright owner that is granting the License. + * + * "Legal Entity" shall mean the union of the acting entity and all + * other entities that control, are controlled by, or are under common + * control with that entity. For the purposes of this definition, + * "control" means (i) the power, direct or indirect, to cause the + * direction or management of such entity, whether by contract or + * otherwise, or (ii) ownership of fifty percent (50%) or more of the + * outstanding shares, or (iii) beneficial ownership of such entity. + * + * "You" (or "Your") shall mean an individual or Legal Entity + * exercising permissions granted by this License. + * + * "Source" form shall mean the preferred form for making modifications, + * including but not limited to software source code, documentation + * source, and configuration files. + * + * "Object" form shall mean any form resulting from mechanical + * transformation or translation of a Source form, including but + * not limited to compiled object code, generated documentation, + * and conversions to other media types. + * + * "Work" shall mean the work of authorship, whether in Source or + * Object form, made available under the License, as indicated by a + * copyright notice that is included in or attached to the work + * (an example is provided in the Appendix below). + * + * "Derivative Works" shall mean any work, whether in Source or Object + * form, that is based on (or derived from) the Work and for which the + * editorial revisions, annotations, elaborations, or other modifications + * represent, as a whole, an original work of authorship. For the purposes + * of this License, Derivative Works shall not include works that remain + * separable from, or merely link (or bind by name) to the interfaces of, + * the Work and Derivative Works thereof. + * + * "Contribution" shall mean any work of authorship, including + * the original version of the Work and any modifications or additions + * to that Work or Derivative Works thereof, that is intentionally + * submitted to Licensor for inclusion in the Work by the copyright owner + * or by an individual or Legal Entity authorized to submit on behalf of + * the copyright owner. For the purposes of this definition, "submitted" + * means any form of electronic, verbal, or written communication sent + * to the Licensor or its representatives, including but not limited to + * communication on electronic mailing lists, source code control systems, + * and issue tracking systems that are managed by, or on behalf of, the + * Licensor for the purpose of discussing and improving the Work, but + * excluding communication that is conspicuously marked or otherwise + * designated in writing by the copyright owner as "Not a Contribution." + * + * "Contributor" shall mean Licensor and any individual or Legal Entity + * on behalf of whom a Contribution has been received by Licensor and + * subsequently incorporated within the Work. + * + * 2. Grant of Copyright License. Subject to the terms and conditions of + * this License, each Contributor hereby grants to You a perpetual, + * worldwide, non-exclusive, no-charge, royalty-free, irrevocable + * copyright license to reproduce, prepare Derivative Works of, + * publicly display, publicly perform, sublicense, and distribute the + * Work and such Derivative Works in Source or Object form. + * + * 3. Grant of Patent License. Subject to the terms and conditions of + * this License, each Contributor hereby grants to You a perpetual, + * worldwide, non-exclusive, no-charge, royalty-free, irrevocable + * (except as stated in this section) patent license to make, have made, + * use, offer to sell, sell, import, and otherwise transfer the Work, + * where such license applies only to those patent claims licensable + * by such Contributor that are necessarily infringed by their + * Contribution(s) alone or by combination of their Contribution(s) + * with the Work to which such Contribution(s) was submitted. If You + * institute patent litigation against any entity (including a + * cross-claim or counterclaim in a lawsuit) alleging that the Work + * or a Contribution incorporated within the Work constitutes direct + * or contributory patent infringement, then any patent licenses + * granted to You under this License for that Work shall terminate + * as of the date such litigation is filed. + * + * 4. Redistribution. You may reproduce and distribute copies of the + * Work or Derivative Works thereof in any medium, with or without + * modifications, and in Source or Object form, provided that You + * meet the following conditions: + * + * (a) You must give any other recipients of the Work or + * Derivative Works a copy of this License; and + * + * (b) You must cause any modified files to carry prominent notices + * stating that You changed the files; and + * + * (c) You must retain, in the Source form of any Derivative Works + * that You distribute, all copyright, patent, trademark, and + * attribution notices from the Source form of the Work, + * excluding those notices that do not pertain to any part of + * the Derivative Works; and + * + * (d) If the Work includes a "NOTICE" text file as part of its + * distribution, then any Derivative Works that You distribute must + * include a readable copy of the attribution notices contained + * within such NOTICE file, excluding those notices that do not + * pertain to any part of the Derivative Works, in at least one + * of the following places: within a NOTICE text file distributed + * as part of the Derivative Works; within the Source form or + * documentation, if provided along with the Derivative Works; or, + * within a display generated by the Derivative Works, if and + * wherever such third-party notices normally appear. The contents + * of the NOTICE file are for informational purposes only and + * do not modify the License. You may add Your own attribution + * notices within Derivative Works that You distribute, alongside + * or as an addendum to the NOTICE text from the Work, provided + * that such additional attribution notices cannot be construed + * as modifying the License. + * + * You may add Your own copyright statement to Your modifications and + * may provide additional or different license terms and conditions + * for use, reproduction, or distribution of Your modifications, or + * for any such Derivative Works as a whole, provided Your use, + * reproduction, and distribution of the Work otherwise complies with + * the conditions stated in this License. + * + * 5. Submission of Contributions. Unless You explicitly state otherwise, + * any Contribution intentionally submitted for inclusion in the Work + * by You to the Licensor shall be under the terms and conditions of + * this License, without any additional terms or conditions. + * Notwithstanding the above, nothing herein shall supersede or modify + * the terms of any separate license agreement you may have executed + * with Licensor regarding such Contributions. + * + * 6. Trademarks. This License does not grant permission to use the trade + * names, trademarks, service marks, or product names of the Licensor, + * except as required for reasonable and customary use in describing the + * origin of the Work and reproducing the content of the NOTICE file. + * + * 7. Disclaimer of Warranty. Unless required by applicable law or + * agreed to in writing, Licensor provides the Work (and each + * Contributor provides its Contributions) on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied, including, without limitation, any warranties or conditions + * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + * PARTICULAR PURPOSE. You are solely responsible for determining the + * appropriateness of using or redistributing the Work and assume any + * risks associated with Your exercise of permissions under this License. + * + * 8. Limitation of Liability. In no event and under no legal theory, + * whether in tort (including negligence), contract, or otherwise, + * unless required by applicable law (such as deliberate and grossly + * negligent acts) or agreed to in writing, shall any Contributor be + * liable to You for damages, including any direct, indirect, special, + * incidental, or consequential damages of any character arising as a + * result of this License or out of the use or inability to use the + * Work (including but not limited to damages for loss of goodwill, + * work stoppage, computer failure or malfunction, or any and all + * other commercial damages or losses), even if such Contributor + * has been advised of the possibility of such damages. + * + * 9. Accepting Warranty or Additional Liability. While redistributing + * the Work or Derivative Works thereof, You may choose to offer, + * and charge a fee for, acceptance of support, warranty, indemnity, + * or other liability obligations and/or rights consistent with this + * License. However, in accepting such obligations, You may act only + * on Your own behalf and on Your sole responsibility, not on behalf + * of any other Contributor, and only if You agree to indemnify, + * defend, and hold each Contributor harmless for any liability + * incurred by, or claims asserted against, such Contributor by reason + * of your accepting any such warranty or additional liability. + * + * END OF TERMS AND CONDITIONS + * + * APPENDIX: How to apply the Apache License to your work. + * + * To apply the Apache License to your work, attach the following + * boilerplate notice, with the fields enclosed by brackets "[]" + * replaced with your own identifying information. (Don't include + * the brackets!) The text should be enclosed in the appropriate + * comment syntax for the file format. We also recommend that a + * file or class name and description of purpose be included on the + * same "printed page" as the copyright notice for easier + * identification within third-party archives. + * + * Copyright [yyyy] [name of copyright owner] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ---- float-tooltip (MIT) ---- + * + * MIT License + * + * Copyright (c) 2022 Vasco Asturiano + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- internmap (ISC) ---- + * + * Copyright 2021 Mike Bostock + * + * Permission to use, copy, modify, and/or distribute this software for any purpose + * with or without fee is hereby granted, provided that the above copyright notice + * and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + * THIS SOFTWARE. + * + * ---- kapsule (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- lodash-es (MIT) ---- + * + * Copyright OpenJS Foundation and other contributors + * + * Based on Underscore.js, copyright Jeremy Ashkenas, + * DocumentCloud and Investigative Reporters & Editors + * + * This software consists of voluntary contributions made by many + * individuals. For exact contribution history, see the revision history + * available at https://github.com/lodash/lodash + * + * The following license applies to all parts of this software except as + * documented below: + * + * ==== + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * ==== + * + * Copyright and related rights for sample code are waived via CC0. Sample + * code is defined as all source code displayed within the prose of the + * documentation. + * + * CC0: http://creativecommons.org/publicdomain/zero/1.0/ + * + * ==== + * + * Files located in the node_modules and vendor directories are externally + * maintained libraries used by this software which have their own + * licenses; we recommend you read them, as their terms may differ from the + * terms above. + * + * ---- ngraph.events (BSD-3-Clause) ---- + * + * Copyright (c) 2013-2025 Andrei Kashcha + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * Neither the name of the Andrei Kashcha nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ---- ngraph.forcelayout (BSD-3-Clause) ---- + * + * Copyright (c) 2013 - 2022, Andrei Kashcha + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * * Neither the name of the Andrei Kashcha nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ---- ngraph.graph (BSD-3-Clause) ---- + * + * Copyright (c) 2013 - 2026, Andrei Kashcha + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * Neither the name of the Andrei Kashcha nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ---- ngraph.merge (MIT) ---- + * + * The MIT License (MIT) + * + * Copyright (c) 2013-2019 Andrei Kashcha + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- ngraph.random (BSD-3-Clause) ---- + * + * Copyright (c) 2013-2025, Andrei Kashcha + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, this + * list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * Neither the name of the Andrei Kashcha nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ---- polished (MIT) ---- + * + * MIT License + * + * Copyright (c) 2016-Present Brian Hough and Maximilian Stoiber + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- preact (MIT) ---- + * + * The MIT License (MIT) + * + * Copyright (c) 2015-present Jason Miller + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- three (MIT) ---- + * + * The MIT License + * + * Copyright © 2010-2026 three.js authors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * ---- three-forcegraph (MIT) ---- + * + * MIT License + * + * Copyright (c) 2017 Vasco Asturiano + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- three-render-objects (MIT) ---- + * + * MIT License + * + * Copyright (c) 2018 Vasco Asturiano + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * ---- tinycolor2 (MIT) ---- + * + * Copyright (c), Brian Grinstead, http://briangrinstead.com + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +// Version 1.77.0 3d-force-graph - https://github.com/vasturiano/3d-force-graph +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).ForceGraph3D=t()}(this,(function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n>8&255]+Mt[e>>16&255]+Mt[e>>24&255]+"-"+Mt[255&t]+Mt[t>>8&255]+"-"+Mt[t>>16&15|64]+Mt[t>>24&255]+"-"+Mt[63&n|128]+Mt[n>>8&255]+"-"+Mt[n>>16&255]+Mt[n>>24&255]+Mt[255&i]+Mt[i>>8&255]+Mt[i>>16&255]+Mt[i>>24&255]).toLowerCase()}function Ct(e,t,n){return Math.max(t,Math.min(n,e))}function Nt(e,t){return(e%t+t)%t}function Pt(e,t,n){return(1-n)*e+n*t}function Dt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function Ut(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const Lt={DEG2RAD:wt,RAD2DEG:At,generateUUID:Rt,clamp:Ct,euclideanModulo:Nt,mapLinear:function(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)},inverseLerp:function(e,t,n){return e!==t?(n-e)/(t-e):0},lerp:Pt,damp:function(e,t,n,i){return Pt(e,t,1-Math.exp(-n*i))},pingpong:function(e,t=1){return t-Math.abs(Nt(e,2*t)-t)},smoothstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*(3-2*e)},smootherstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(Et=e);let t=Et+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*wt},radToDeg:function(e){return e*At},isPowerOfTwo:function(e){return!(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),u=s((t+i)/2),c=a((t+i)/2),h=s((t-i)/2),d=a((t-i)/2),p=s((i-t)/2),f=a((i-t)/2);switch(r){case"XYX":e.set(o*c,l*h,l*d,o*u);break;case"YZY":e.set(l*d,o*c,l*h,o*u);break;case"ZXZ":e.set(l*h,l*d,o*c,o*u);break;case"XZX":e.set(o*c,l*f,l*p,o*u);break;case"YXY":e.set(l*p,o*c,l*f,o*u);break;case"ZYZ":e.set(l*f,l*p,o*c,o*u);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Ut,denormalize:Dt};class It{constructor(e=0,t=0){It.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Ct(this.x,e.x,t.x),this.y=Ct(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ct(this.x,e,t),this.y=Ct(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ct(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Ct(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),i=Math.sin(t),r=this.x-e.x,s=this.y-e.y;return this.x=r*n-s*i+e.x,this.y=r*i+s*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Ot{constructor(e,t,n,i,r,s,a,o,l){Ot.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l)}set(e,t,n,i,r,s,a,o,l){const u=this.elements;return u[0]=e,u[1]=i,u[2]=a,u[3]=t,u[4]=r,u[5]=o,u[6]=n,u[7]=s,u[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],u=n[4],c=n[7],h=n[2],d=n[5],p=n[8],f=i[0],m=i[3],g=i[6],_=i[1],v=i[4],y=i[7],x=i[2],b=i[5],S=i[8];return r[0]=s*f+a*_+o*x,r[3]=s*m+a*v+o*b,r[6]=s*g+a*y+o*S,r[1]=l*f+u*_+c*x,r[4]=l*m+u*v+c*b,r[7]=l*g+u*y+c*S,r[2]=h*f+d*_+p*x,r[5]=h*m+d*v+p*b,r[8]=h*g+d*y+p*S,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8];return t*s*u-t*a*l-n*r*u+n*a*o+i*r*l-i*s*o}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=u*s-a*l,h=a*o-u*r,d=l*r-s*o,p=t*c+n*h+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const f=1/p;return e[0]=c*f,e[1]=(i*l-u*n)*f,e[2]=(a*n-i*s)*f,e[3]=h*f,e[4]=(u*t-i*o)*f,e[5]=(i*r-a*t)*f,e[6]=d*f,e[7]=(n*o-l*t)*f,e[8]=(s*t-n*r)*f,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+e,-i*l,i*o,-i*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Ft.makeScale(e,t)),this}rotate(e){return this.premultiply(Ft.makeRotation(-e)),this}translate(e,t){return this.premultiply(Ft.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const Ft=new Ot;function Bt(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function kt(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function zt(){const e=kt("canvas");return e.style.display="block",e}const Gt={};function Vt(e){e in Gt||(Gt[e]=!0,console.warn(e))}const Ht=(new Ot).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),jt=(new Ot).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Wt(){const e={enabled:!0,workingColorSpace:at,spaces:{},convert:function(e,t,n){return!1!==this.enabled&&t!==n&&t&&n?(this.spaces[t].transfer===lt&&(e.r=qt(e.r),e.g=qt(e.g),e.b=qt(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===lt&&(e.r=$t(e.r),e.g=$t(e.g),e.b=$t(e.b)),e):e},fromWorkingColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},toWorkingColorSpace:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===rt?ot:this.spaces[e].transfer},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[at]:{primaries:t,whitePoint:i,transfer:ot,toXYZ:Ht,fromXYZ:jt,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:st},outputColorSpaceConfig:{drawingBufferColorSpace:st}},[st]:{primaries:t,whitePoint:i,transfer:lt,toXYZ:Ht,fromXYZ:jt,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:st}}}),e}const Xt=Wt();function qt(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function $t(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Yt;class Kt{static getDataURL(e){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{void 0===Yt&&(Yt=kt("canvas")),Yt.width=e.width,Yt.height=e.height;const n=Yt.getContext("2d");e instanceof ImageData?n.putImageData(e,0,0):n.drawImage(e,0,0,e.width,e.height),t=Yt}return t.toDataURL("image/png")}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=kt("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(300!==this.mapping)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case q:e.x=e.x-Math.floor(e.x);break;case $:e.x=e.x<0?0:1;break;case Y:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case q:e.y=e.y-Math.floor(e.y);break;case $:e.y=e.y<0?0:1;break;case Y:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}tn.DEFAULT_IMAGE=null,tn.DEFAULT_MAPPING=300,tn.DEFAULT_ANISOTROPY=1;class nn{constructor(e=0,t=0,n=0,i=1){nn.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*t+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*t+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*t+s[7]*n+s[11]*i+s[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,i,r;const s=.01,a=.1,o=e.elements,l=o[0],u=o[4],c=o[8],h=o[1],d=o[5],p=o[9],f=o[2],m=o[6],g=o[10];if(Math.abs(u-h)o&&e>_?e_?o=0?1:-1,i=1-t*t;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,t*n);e=Math.sin(e*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*e+h*r,l=l*e+d*r,u=u*e+p*r,c=c*e+f*r,e===1-a){const e=1/Math.sqrt(o*o+l*l+u*u+c*c);o*=e,l*=e,u*=e,c*=e}}e[t]=o,e[t+1]=l,e[t+2]=u,e[t+3]=c}static multiplyQuaternionsFlat(e,t,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],u=n[i+3],c=r[s],h=r[s+1],d=r[s+2],p=r[s+3];return e[t]=a*p+u*c+o*d-l*h,e[t+1]=o*p+u*h+l*c-a*d,e[t+2]=l*p+u*d+a*h-o*c,e[t+3]=u*p-a*c-o*h-l*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,i=e._y,r=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(n/2),u=a(i/2),c=a(r/2),h=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"YXZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"ZXY":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"ZYX":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"YZX":this._x=h*u*c+l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c-h*d*p;break;case"XZY":this._x=h*u*c-l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c+h*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],i=t[4],r=t[8],s=t[1],a=t[5],o=t[9],l=t[2],u=t[6],c=t[10],h=n+a+c;if(h>0){const e=.5/Math.sqrt(h+1);this._w=.25/e,this._x=(u-o)*e,this._y=(r-l)*e,this._z=(s-i)*e}else if(n>a&&n>c){const e=2*Math.sqrt(1+n-a-c);this._w=(u-o)/e,this._x=.25*e,this._y=(i+s)/e,this._z=(r+l)/e}else if(a>c){const e=2*Math.sqrt(1+a-n-c);this._w=(r-l)/e,this._x=(i+s)/e,this._y=.25*e,this._z=(o+u)/e}else{const e=2*Math.sqrt(1+c-n-a);this._w=(s-i)/e,this._x=(r+l)/e,this._y=(o+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return nMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Ct(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(0===n)return this;const i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,i=e._y,r=e._z,s=e._w,a=t._x,o=t._y,l=t._z,u=t._w;return this._x=n*u+s*a+i*l-r*o,this._y=i*u+s*o+r*a-n*l,this._z=r*u+s*l+n*o-i*a,this._w=s*u-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*e._w+n*e._x+i*e._y+r*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=s,this._x=n,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const e=1-t;return this._w=e*s+t*this._w,this._x=e*n+t*this._x,this._y=e*i+t*this._y,this._z=e*r+t*this._z,this.normalize(),this}const l=Math.sqrt(o),u=Math.atan2(l,a),c=Math.sin((1-t)*u)/l,h=Math.sin(t*u)/l;return this._w=s*c+this._w*h,this._x=n*c+this._x*h,this._y=i*c+this._y*h,this._z=r*c+this._z*h,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class un{constructor(e=0,t=0,n=0){un.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return void 0===n&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(hn.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(hn.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*i,this.y=r[1]*t+r[4]*n+r[7]*i,this.z=r[2]*t+r[5]*n+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,r=e.elements,s=1/(r[3]*t+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*t+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*t+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,r=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*i-a*n),u=2*(a*t-r*i),c=2*(r*n-s*t);return this.x=t+o*l+s*c-a*u,this.y=n+o*u+a*l-r*c,this.z=i+o*c+r*u-s*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*i,this.y=r[1]*t+r[5]*n+r[9]*i,this.z=r[2]*t+r[6]*n+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Ct(this.x,e.x,t.x),this.y=Ct(this.y,e.y,t.y),this.z=Ct(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ct(this.x,e,t),this.y=Ct(this.y,e,t),this.z=Ct(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ct(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,i=e.y,r=e.z,s=t.x,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return cn.copy(this).projectOnVector(e),this.sub(cn)}reflect(e){return this.sub(cn.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(Ct(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const cn=new un,hn=new ln;class dn{constructor(e=new un(1/0,1/0,1/0),t=new un(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,fn),fn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Sn),Tn.subVectors(this.max,Sn),gn.subVectors(e.a,Sn),_n.subVectors(e.b,Sn),vn.subVectors(e.c,Sn),yn.subVectors(_n,gn),xn.subVectors(vn,_n),bn.subVectors(gn,vn);let t=[0,-yn.z,yn.y,0,-xn.z,xn.y,0,-bn.z,bn.y,yn.z,0,-yn.x,xn.z,0,-xn.x,bn.z,0,-bn.x,-yn.y,yn.x,0,-xn.y,xn.x,0,-bn.y,bn.x,0];return!!wn(t,gn,_n,vn,Tn)&&(t=[1,0,0,0,1,0,0,0,1],!!wn(t,gn,_n,vn,Tn)&&(Mn.crossVectors(yn,xn),t=[Mn.x,Mn.y,Mn.z],wn(t,gn,_n,vn,Tn)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,fn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(fn).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(pn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),pn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),pn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),pn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),pn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),pn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),pn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),pn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(pn)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const pn=[new un,new un,new un,new un,new un,new un,new un,new un],fn=new un,mn=new dn,gn=new un,_n=new un,vn=new un,yn=new un,xn=new un,bn=new un,Sn=new un,Tn=new un,Mn=new un,En=new un;function wn(e,t,n,i,r){for(let s=0,a=e.length-3;s<=a;s+=3){En.fromArray(e,s);const a=r.x*Math.abs(En.x)+r.y*Math.abs(En.y)+r.z*Math.abs(En.z),o=t.dot(En),l=n.dot(En),u=i.dot(En);if(Math.max(-Math.max(o,l,u),Math.min(o,l,u))>a)return!1}return!0}const An=new dn,Rn=new un,Cn=new un;class Nn{constructor(e=new un,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;void 0!==t?n.copy(t):An.setFromPoints(e).getCenter(n);let i=0;for(let t=0,r=e.length;tthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Rn.subVectors(e,this.center);const t=Rn.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector(Rn,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(Cn.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Rn.copy(e.center).add(Cn)),this.expandByPoint(Rn.copy(e.center).sub(Cn))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const Pn=new un,Dn=new un,Un=new un,Ln=new un,In=new un,On=new un,Fn=new un;class Bn{constructor(e=new un,t=new un(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Pn)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Pn.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Pn.copy(this.origin).addScaledVector(this.direction,t),Pn.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){Dn.copy(e).add(t).multiplyScalar(.5),Un.copy(t).sub(e).normalize(),Ln.copy(this.origin).sub(Dn);const r=.5*e.distanceTo(t),s=-this.direction.dot(Un),a=Ln.dot(this.direction),o=-Ln.dot(Un),l=Ln.lengthSq(),u=Math.abs(1-s*s);let c,h,d,p;if(u>0)if(c=s*o-a,h=s*a-o,p=r*u,c>=0)if(h>=-p)if(h<=p){const e=1/u;c*=e,h*=e,d=c*(c+s*h+2*a)+h*(s*c+h+2*o)+l}else h=r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h=-r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h<=-p?(c=Math.max(0,-(-s*r+a)),h=c>0?-r:Math.min(Math.max(-r,-o),r),d=-c*c+h*(h+2*o)+l):h<=p?(c=0,h=Math.min(Math.max(-r,-o),r),d=h*(h+2*o)+l):(c=Math.max(0,-(s*r+a)),h=c>0?r:Math.min(Math.max(-r,-o),r),d=-c*c+h*(h+2*o)+l);else h=s>0?-r:r,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,c),i&&i.copy(Dn).addScaledVector(Un,h),d}intersectSphere(e,t){Pn.subVectors(e.center,this.origin);const n=Pn.dot(this.direction),i=Pn.dot(Pn)-n*n,r=e.radius*e.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return null===n?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,r,s,a,o;const l=1/this.direction.x,u=1/this.direction.y,c=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,i=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,i=(e.min.x-h.x)*l),u>=0?(r=(e.min.y-h.y)*u,s=(e.max.y-h.y)*u):(r=(e.max.y-h.y)*u,s=(e.min.y-h.y)*u),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s=0?(a=(e.min.z-h.z)*c,o=(e.max.z-h.z)*c):(a=(e.max.z-h.z)*c,o=(e.min.z-h.z)*c),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o=0?n:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Pn)}intersectTriangle(e,t,n,i,r){In.subVectors(t,e),On.subVectors(n,e),Fn.crossVectors(In,On);let s,a=this.direction.dot(Fn);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}Ln.subVectors(this.origin,e);const o=s*this.direction.dot(On.crossVectors(Ln,On));if(o<0)return null;const l=s*this.direction.dot(In.cross(Ln));if(l<0)return null;if(o+l>a)return null;const u=-s*Ln.dot(Fn);return u<0?null:this.at(u/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class kn{constructor(e,t,n,i,r,s,a,o,l,u,c,h,d,p,f,m){kn.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,n,i,r,s,a,o,l,u,c,h,d,p,f,m)}set(e,t,n,i,r,s,a,o,l,u,c,h,d,p,f,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=u,g[10]=c,g[14]=h,g[3]=d,g[7]=p,g[11]=f,g[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new kn).fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,i=1/zn.setFromMatrixColumn(e,0).length(),r=1/zn.setFromMatrixColumn(e,1).length(),s=1/zn.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*s,t[9]=n[9]*s,t[10]=n[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,i=e.y,r=e.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),u=Math.cos(r),c=Math.sin(r);if("XYZ"===e.order){const e=s*u,n=s*c,i=a*u,r=a*c;t[0]=o*u,t[4]=-o*c,t[8]=l,t[1]=n+i*l,t[5]=e-r*l,t[9]=-a*o,t[2]=r-e*l,t[6]=i+n*l,t[10]=s*o}else if("YXZ"===e.order){const e=o*u,n=o*c,i=l*u,r=l*c;t[0]=e+r*a,t[4]=i*a-n,t[8]=s*l,t[1]=s*c,t[5]=s*u,t[9]=-a,t[2]=n*a-i,t[6]=r+e*a,t[10]=s*o}else if("ZXY"===e.order){const e=o*u,n=o*c,i=l*u,r=l*c;t[0]=e-r*a,t[4]=-s*c,t[8]=i+n*a,t[1]=n+i*a,t[5]=s*u,t[9]=r-e*a,t[2]=-s*l,t[6]=a,t[10]=s*o}else if("ZYX"===e.order){const e=s*u,n=s*c,i=a*u,r=a*c;t[0]=o*u,t[4]=i*l-n,t[8]=e*l+r,t[1]=o*c,t[5]=r*l+e,t[9]=n*l-i,t[2]=-l,t[6]=a*o,t[10]=s*o}else if("YZX"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*u,t[4]=r-e*c,t[8]=i*c+n,t[1]=c,t[5]=s*u,t[9]=-a*u,t[2]=-l*u,t[6]=n*c+i,t[10]=e-r*c}else if("XZY"===e.order){const e=s*o,n=s*l,i=a*o,r=a*l;t[0]=o*u,t[4]=-c,t[8]=l*u,t[1]=e*c+r,t[5]=s*u,t[9]=n*c-i,t[2]=i*c-n,t[6]=a*u,t[10]=r*c+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(Vn,e,Hn)}lookAt(e,t,n){const i=this.elements;return Xn.subVectors(e,t),0===Xn.lengthSq()&&(Xn.z=1),Xn.normalize(),jn.crossVectors(n,Xn),0===jn.lengthSq()&&(1===Math.abs(n.z)?Xn.x+=1e-4:Xn.z+=1e-4,Xn.normalize(),jn.crossVectors(n,Xn)),jn.normalize(),Wn.crossVectors(Xn,jn),i[0]=jn.x,i[4]=Wn.x,i[8]=Xn.x,i[1]=jn.y,i[5]=Wn.y,i[9]=Xn.y,i[2]=jn.z,i[6]=Wn.z,i[10]=Xn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,i=t.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],u=n[1],c=n[5],h=n[9],d=n[13],p=n[2],f=n[6],m=n[10],g=n[14],_=n[3],v=n[7],y=n[11],x=n[15],b=i[0],S=i[4],T=i[8],M=i[12],E=i[1],w=i[5],A=i[9],R=i[13],C=i[2],N=i[6],P=i[10],D=i[14],U=i[3],L=i[7],I=i[11],O=i[15];return r[0]=s*b+a*E+o*C+l*U,r[4]=s*S+a*w+o*N+l*L,r[8]=s*T+a*A+o*P+l*I,r[12]=s*M+a*R+o*D+l*O,r[1]=u*b+c*E+h*C+d*U,r[5]=u*S+c*w+h*N+d*L,r[9]=u*T+c*A+h*P+d*I,r[13]=u*M+c*R+h*D+d*O,r[2]=p*b+f*E+m*C+g*U,r[6]=p*S+f*w+m*N+g*L,r[10]=p*T+f*A+m*P+g*I,r[14]=p*M+f*R+m*D+g*O,r[3]=_*b+v*E+y*C+x*U,r[7]=_*S+v*w+y*N+x*L,r[11]=_*T+v*A+y*P+x*I,r[15]=_*M+v*R+y*D+x*O,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],i=e[8],r=e[12],s=e[1],a=e[5],o=e[9],l=e[13],u=e[2],c=e[6],h=e[10],d=e[14];return e[3]*(+r*o*c-i*l*c-r*a*h+n*l*h+i*a*d-n*o*d)+e[7]*(+t*o*d-t*l*h+r*s*h-i*s*d+i*l*u-r*o*u)+e[11]*(+t*l*c-t*a*d-r*s*c+n*s*d+r*a*u-n*l*u)+e[15]*(-i*a*u-t*o*c+t*a*h+i*s*c-n*s*h+n*o*u)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],r=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],d=e[11],p=e[12],f=e[13],m=e[14],g=e[15],_=c*m*l-f*h*l+f*o*d-a*m*d-c*o*g+a*h*g,v=p*h*l-u*m*l-p*o*d+s*m*d+u*o*g-s*h*g,y=u*f*l-p*c*l+p*a*d-s*f*d-u*a*g+s*c*g,x=p*c*o-u*f*o-p*a*h+s*f*h+u*a*m-s*c*m,b=t*_+n*v+i*y+r*x;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const S=1/b;return e[0]=_*S,e[1]=(f*h*r-c*m*r-f*i*d+n*m*d+c*i*g-n*h*g)*S,e[2]=(a*m*r-f*o*r+f*i*l-n*m*l-a*i*g+n*o*g)*S,e[3]=(c*o*r-a*h*r-c*i*l+n*h*l+a*i*d-n*o*d)*S,e[4]=v*S,e[5]=(u*m*r-p*h*r+p*i*d-t*m*d-u*i*g+t*h*g)*S,e[6]=(p*o*r-s*m*r-p*i*l+t*m*l+s*i*g-t*o*g)*S,e[7]=(s*h*r-u*o*r+u*i*l-t*h*l-s*i*d+t*o*d)*S,e[8]=y*S,e[9]=(p*c*r-u*f*r-p*n*d+t*f*d+u*n*g-t*c*g)*S,e[10]=(s*f*r-p*a*r+p*n*l-t*f*l-s*n*g+t*a*g)*S,e[11]=(u*a*r-s*c*r-u*n*l+t*c*l+s*n*d-t*a*d)*S,e[12]=x*S,e[13]=(u*f*i-p*c*i+p*n*h-t*f*h-u*n*m+t*c*m)*S,e[14]=(p*a*i-s*f*i-p*n*o+t*f*o+s*n*m-t*a*m)*S,e[15]=(s*c*i-u*a*i+u*n*o-t*c*o-s*n*h+t*a*h)*S,this}scale(e){const t=this.elements,n=e.x,i=e.y,r=e.z;return t[0]*=n,t[4]*=i,t[8]*=r,t[1]*=n,t[5]*=i,t[9]*=r,t[2]*=n,t[6]*=i,t[10]*=r,t[3]*=n,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),i=Math.sin(t),r=1-n,s=e.x,a=e.y,o=e.z,l=r*s,u=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,u*a+n,u*o-i*s,0,l*o-i*a,u*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,r,s){return this.set(1,n,r,0,e,1,s,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,r=t._x,s=t._y,a=t._z,o=t._w,l=r+r,u=s+s,c=a+a,h=r*l,d=r*u,p=r*c,f=s*u,m=s*c,g=a*c,_=o*l,v=o*u,y=o*c,x=n.x,b=n.y,S=n.z;return i[0]=(1-(f+g))*x,i[1]=(d+y)*x,i[2]=(p-v)*x,i[3]=0,i[4]=(d-y)*b,i[5]=(1-(h+g))*b,i[6]=(m+_)*b,i[7]=0,i[8]=(p+v)*S,i[9]=(m-_)*S,i[10]=(1-(h+f))*S,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){const i=this.elements;let r=zn.set(i[0],i[1],i[2]).length();const s=zn.set(i[4],i[5],i[6]).length(),a=zn.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),e.x=i[12],e.y=i[13],e.z=i[14],Gn.copy(this);const o=1/r,l=1/s,u=1/a;return Gn.elements[0]*=o,Gn.elements[1]*=o,Gn.elements[2]*=o,Gn.elements[4]*=l,Gn.elements[5]*=l,Gn.elements[6]*=l,Gn.elements[8]*=u,Gn.elements[9]*=u,Gn.elements[10]*=u,t.setFromRotationMatrix(Gn),n.x=r,n.y=s,n.z=a,this}makePerspective(e,t,n,i,r,s,a=2e3){const o=this.elements,l=2*r/(t-e),u=2*r/(n-i),c=(t+e)/(t-e),h=(n+i)/(n-i);let d,p;if(a===bt)d=-(s+r)/(s-r),p=-2*s*r/(s-r);else{if(a!==St)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-s/(s-r),p=-s*r/(s-r)}return o[0]=l,o[4]=0,o[8]=c,o[12]=0,o[1]=0,o[5]=u,o[9]=h,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(e,t,n,i,r,s,a=2e3){const o=this.elements,l=1/(t-e),u=1/(n-i),c=1/(s-r),h=(t+e)*l,d=(n+i)*u;let p,f;if(a===bt)p=(s+r)*c,f=-2*c;else{if(a!==St)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*c,f=-1*c}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-h,o[1]=0,o[5]=2*u,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=f,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const zn=new un,Gn=new kn,Vn=new un(0,0,0),Hn=new un(1,1,1),jn=new un,Wn=new un,Xn=new un,qn=new kn,$n=new ln;class Yn{constructor(e=0,t=0,n=0,i=Yn.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const i=e.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],u=i[9],c=i[2],h=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Ct(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Ct(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-c,r),this._z=0);break;case"ZXY":this._x=Math.asin(Ct(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Ct(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(h,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(Ct(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,l),this._y=Math.atan2(-c,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Ct(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-u,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return qn.makeRotationFromQuaternion(e),this.setFromRotationMatrix(qn,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return $n.setFromEuler(this),this.setFromQuaternion($n,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Yn.DEFAULT_ORDER="XYZ";class Kn{constructor(){this.mask=1}set(e){this.mask=1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((e=>({boxInitialized:e.boxInitialized,boxMin:e.box.min.toArray(),boxMax:e.box.max.toArray(),sphereInitialized:e.sphereInitialized,sphereRadius:e.sphere.radius,sphereCenter:e.sphere.center.toArray()}))),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const n=t.shapes;if(Array.isArray(n))for(let t=0,i=n.length;t0){i.children=[];for(let t=0;t0){i.animations=[];for(let t=0;t0&&(n.geometries=t),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),u.length>0&&(n.animations=u),c.length>0&&(n.nodes=c)}return n.object=i,n;function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,n,i,r){pi.subVectors(i,t),fi.subVectors(n,t),mi.subVectors(e,t);const s=pi.dot(pi),a=pi.dot(fi),o=pi.dot(mi),l=fi.dot(fi),u=fi.dot(mi),c=s*l-a*a;if(0===c)return r.set(0,0,0),null;const h=1/c,d=(l*o-a*u)*h,p=(s*u-a*o)*h;return r.set(1-d-p,p,d)}static containsPoint(e,t,n,i){return null!==this.getBarycoord(e,t,n,i,gi)&&(gi.x>=0&&gi.y>=0&&gi.x+gi.y<=1)}static getInterpolation(e,t,n,i,r,s,a,o){return null===this.getBarycoord(e,t,n,i,gi)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,gi.x),o.addScaledVector(s,gi.y),o.addScaledVector(a,gi.z),o)}static getInterpolatedAttribute(e,t,n,i,r,s){return Ti.setScalar(0),Mi.setScalar(0),Ei.setScalar(0),Ti.fromBufferAttribute(e,t),Mi.fromBufferAttribute(e,n),Ei.fromBufferAttribute(e,i),s.setScalar(0),s.addScaledVector(Ti,r.x),s.addScaledVector(Mi,r.y),s.addScaledVector(Ei,r.z),s}static isFrontFacing(e,t,n,i){return pi.subVectors(n,t),fi.subVectors(e,t),pi.cross(fi).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return pi.subVectors(this.c,this.b),fi.subVectors(this.a,this.b),.5*pi.cross(fi).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return wi.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return wi.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,r){return wi.getInterpolation(e,this.a,this.b,this.c,t,n,i,r)}containsPoint(e){return wi.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return wi.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,r=this.c;let s,a;_i.subVectors(i,n),vi.subVectors(r,n),xi.subVectors(e,n);const o=_i.dot(xi),l=vi.dot(xi);if(o<=0&&l<=0)return t.copy(n);bi.subVectors(e,i);const u=_i.dot(bi),c=vi.dot(bi);if(u>=0&&c<=u)return t.copy(i);const h=o*c-u*l;if(h<=0&&o>=0&&u<=0)return s=o/(o-u),t.copy(n).addScaledVector(_i,s);Si.subVectors(e,r);const d=_i.dot(Si),p=vi.dot(Si);if(p>=0&&d<=p)return t.copy(r);const f=d*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(n).addScaledVector(vi,a);const m=u*p-d*c;if(m<=0&&c-u>=0&&d-p>=0)return yi.subVectors(r,i),a=(c-u)/(c-u+(d-p)),t.copy(i).addScaledVector(yi,a);const g=1/(m+f+h);return s=f*g,a=h*g,t.copy(n).addScaledVector(_i,s).addScaledVector(vi,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Ai={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ri={h:0,s:0,l:0},Ci={h:0,s:0,l:0};function Ni(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}class Pi{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(void 0===t&&void 0===n){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=st){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,Xt.toWorkingColorSpace(this,t),this}setRGB(e,t,n,i=Xt.workingColorSpace){return this.r=e,this.g=t,this.b=n,Xt.toWorkingColorSpace(this,i),this}setHSL(e,t,n,i=Xt.workingColorSpace){if(e=Nt(e,1),t=Ct(t,0,1),n=Ct(n,0,1),0===t)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+t):n+t-n*t,r=2*n-i;this.r=Ni(r,i,e+1/3),this.g=Ni(r,i,e),this.b=Ni(r,i,e-1/3)}return Xt.toWorkingColorSpace(this,i),this}setStyle(e,t=st){function n(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(n,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=st){const n=Ai[e.toLowerCase()];return void 0!==n?this.setHex(n,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=qt(e.r),this.g=qt(e.g),this.b=qt(e.b),this}copyLinearToSRGB(e){return this.r=$t(e.r),this.g=$t(e.g),this.b=$t(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=st){return Xt.fromWorkingColorSpace(Di.copy(this),e),65536*Math.round(Ct(255*Di.r,0,255))+256*Math.round(Ct(255*Di.g,0,255))+Math.round(Ct(255*Di.b,0,255))}getHexString(e=st){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Xt.workingColorSpace){Xt.fromWorkingColorSpace(Di.copy(this),t);const n=Di.r,i=Di.g,r=Di.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const u=(a+s)/2;if(a===s)o=0,l=0;else{const e=s-a;switch(l=u<=.5?e/(s+a):e/(2-s-a),s){case n:o=(i-r)/e+(i0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const n=e[t];if(void 0===n){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n:console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.dispersion&&(n.dispersion=this.dispersion),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==T&&(n.blendSrc=this.blendSrc),this.blendDst!==M&&(n.blendDst=this.blendDst),this.blendEquation!==g&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ut&&(n.stencilFail=this.stencilFail),this.stencilZFail!==ut&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==ut&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(n.textures=t),r.length>0&&(n.images=r)}return n}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(null!==t){const e=t.length;n=new Array(e);for(let i=0;i!==e;++i)n[i]=t[i].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class Ii extends Li{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Pi(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Oi=Fi();function Fi(){const e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(8388608&t);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,s[e]=t|n}for(let e=1024;e<2048;++e)s[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function Bi(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=Ct(e,-65504,65504),Oi.floatView[0]=e;const t=Oi.uint32View[0],n=t>>23&511;return Oi.baseTable[n]+((8388607&t)>>Oi.shiftTable[n])}function ki(e){const t=e>>10;return Oi.uint32View[0]=Oi.mantissaTable[Oi.offsetTable[t]+(1023&e)]+Oi.exponentTable[t],Oi.floatView[0]}const zi=new un,Gi=new It;let Vi=0;class Hi{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Vi++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=n,this.usage=vt,this.updateRanges=[],this.gpuType=le,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let i=0,r=this.itemSize;it.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new dn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new un(-1/0,-1/0,-1/0),new un(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const t in n){const i=n[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const n=this.morphAttributes[t],s=[];for(let t=0,i=n.length;t0&&(i[t]=s,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(e.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;null!==n&&this.setIndex(n.clone(t));const i=e.attributes;for(const e in i){const n=i[e];this.setAttribute(e,n.clone(t))}const r=e.morphAttributes;for(const e in r){const n=[],i=r[e];for(let e=0,r=i.length;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2)return}nr.copy(r).invert(),ir.copy(e.ray).applyMatrix4(nr),null!==n.boundingBox&&!1===ir.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,ir)}}_computeIntersections(e,t,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,u=r.attributes.uv1,c=r.attributes.normal,h=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=h.length;rn.far?null:{distance:u,point:dr.clone(),object:e}}(e,t,n,i,ar,or,lr,hr);if(c){const e=new un;wi.getBarycoord(hr,ar,or,lr,e),r&&(c.uv=wi.getInterpolatedAttribute(r,o,l,u,e,new It)),s&&(c.uv1=wi.getInterpolatedAttribute(s,o,l,u,e,new It)),a&&(c.normal=wi.getInterpolatedAttribute(a,o,l,u,e,new un),c.normal.dot(i.direction)>0&&c.normal.multiplyScalar(-1));const t={a:o,b:l,c:u,normal:new un,materialIndex:0};wi.getNormal(ar,or,lr,t.normal),c.face=t,c.barycoord=e}return c}class mr extends tr{constructor(e=1,t=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],u=[],c=[];let h=0,d=0;function p(e,t,n,i,r,s,p,f,m,g,_){const v=s/m,y=p/g,x=s/2,b=p/2,S=f/2,T=m+1,M=g+1;let E=0,w=0;const A=new un;for(let s=0;s0?1:-1,u.push(A.x,A.y,A.z),c.push(o/m),c.push(1-s/g),E+=1}}for(let e=0;e0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const e in this.extensions)!0===this.extensions[e]&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class br extends di{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new kn,this.projectionMatrix=new kn,this.projectionMatrixInverse=new kn,this.coordinateSystem=bt}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Sr=new un,Tr=new It,Mr=new It;class Er extends br{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*At*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*wt*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*At*Math.atan(Math.tan(.5*wt*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Sr.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Sr.x,Sr.y).multiplyScalar(-e/Sr.z),Sr.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Sr.x,Sr.y).multiplyScalar(-e/Sr.z)}getViewSize(e,t){return this.getViewBounds(e,Tr,Mr),t.subVectors(Mr,Tr)}setViewOffset(e,t,n,i,r,s){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*wt*this.fov)/this.zoom,n=2*t,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const e=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/e,t-=s.offsetY*n/a,i*=s.width/e,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const wr=-90;class Ar extends di{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Er(wr,1,e,t);i.layers=this.layers,this.add(i);const r=new Er(wr,1,e,t);r.layers=this.layers,this.add(r);const s=new Er(wr,1,e,t);s.layers=this.layers,this.add(s);const a=new Er(wr,1,e,t);a.layers=this.layers,this.add(a);const o=new Er(wr,1,e,t);o.layers=this.layers,this.add(o);const l=new Er(wr,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,i,r,s,a,o]=t;for(const e of t)this.remove(e);if(e===bt)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==St)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,u]=this.children,c=e.getRenderTarget(),h=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const f=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,i),e.render(t,r),e.setRenderTarget(n,1,i),e.render(t,s),e.setRenderTarget(n,2,i),e.render(t,a),e.setRenderTarget(n,3,i),e.render(t,o),e.setRenderTarget(n,4,i),e.render(t,l),n.texture.generateMipmaps=f,e.setRenderTarget(n,5,i),e.render(t,u),e.setRenderTarget(c,h,d),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class Rr extends tn{constructor(e,t,n,i,r,s,a,o,l,u){super(e=void 0!==e?e:[],t=void 0!==t?t:V,n,i,r,s,a,o,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Cr extends sn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new Rr(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==t.generateMipmaps&&t.generateMipmaps,this.texture.minFilter=void 0!==t.minFilter?t.minFilter:J}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new mr(5,5,5),r=new xr({name:"CubemapFromEquirect",uniforms:gr(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const s=new pr(i,r),a=t.minFilter;t.minFilter===te&&(t.minFilter=J);return new Ar(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t,n,i){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,n,i);e.setRenderTarget(r)}}let Nr=class extends di{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Pr={type:"move"};class Dr{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Nr,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new Nr,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new un,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new un),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Nr,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new un,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new un),this._grip}dispatchEvent(e){return null!==this._targetRay&&this._targetRay.dispatchEvent(e),null!==this._grip&&this._grip.dispatchEvent(e),null!==this._hand&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(e,t,n){let i=null,r=null,s=null;const a=this._targetRay,o=this._grip,l=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(l&&e.hand){s=!0;for(const i of e.hand.values()){const e=t.getJointPose(i,n),r=this._getHandJoint(l,i);null!==e&&(r.matrix.fromArray(e.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=e.radius),r.visible=null!==e}const i=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],a=i.position.distanceTo(r.position),o=.02,u=.005;l.inputState.pinching&&a>o+u?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-u&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(i=t.getPose(e.targetRaySpace,n),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Pr)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const n=new Nr;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class Ur extends di{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Yn,this.environmentIntensity=1,this.environmentRotation=new Yn,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Lr{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=vt,this.updateRanges=[],this.version=0,this.uuid=Rt()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,r=this.stride;i1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||Vr.getNormalMatrix(e),i=this.coplanarPoint(zr).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const jr=new Nn,Wr=new un;class Xr{constructor(e=new Hr,t=new Hr,n=new Hr,i=new Hr,r=new Hr,s=new Hr){this.planes=[e,t,n,i,r,s]}set(e,t,n,i,r,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3){const n=this.planes,i=e.elements,r=i[0],s=i[1],a=i[2],o=i[3],l=i[4],u=i[5],c=i[6],h=i[7],d=i[8],p=i[9],f=i[10],m=i[11],g=i[12],_=i[13],v=i[14],y=i[15];if(n[0].setComponents(o-r,h-l,m-d,y-g).normalize(),n[1].setComponents(o+r,h+l,m+d,y+g).normalize(),n[2].setComponents(o+s,h+u,m+p,y+_).normalize(),n[3].setComponents(o-s,h-u,m-p,y-_).normalize(),n[4].setComponents(o-a,h-c,m-f,y-v).normalize(),t===bt)n[5].setComponents(o+a,h+c,m+f,y+v).normalize();else{if(t!==St)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);n[5].setComponents(a,c,f,v).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),jr.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),jr.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(jr)}intersectsSprite(e){return jr.center.set(0,0,0),jr.radius=.7071067811865476,jr.applyMatrix4(e.matrixWorld),this.intersectsSphere(jr)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,Wr.y=i.normal.y>0?e.max.y:e.min.y,Wr.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Wr)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}class qr extends Li{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Pi(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const $r=new un,Yr=new un,Kr=new kn,Zr=new Bn,Qr=new Nn,Jr=new un,es=new un;function ts(e,t,n,i,r,s,a){const o=e.geometry.attributes.position;$r.fromBufferAttribute(o,r),Yr.fromBufferAttribute(o,s);if(n.distanceSqToSegment($r,Yr,Jr,es)>i)return;Jr.applyMatrix4(e.matrixWorld);const l=t.ray.origin.distanceTo(Jr);return lt.far?void 0:{distance:l,point:es.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}class ns extends Li{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Pi(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class is extends tn{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=K,this.minFilter=K,this.generateMipmaps=!1,this.needsUpdate=!0}}class rs extends tn{constructor(e,t,n,i,r,s,a,o,l,u=1026){if(u!==ye&&u!==xe)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");void 0===n&&u===ye&&(n=oe),void 0===n&&u===xe&&(n=de),super(null,i,r,s,a,o,u,n,l),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=void 0!==a?a:K,this.minFilter=void 0!==o?o:K,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Qt(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class ss{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){console.warn("THREE.Curve: .getPoint() not implemented.")}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,i=this.getPoint(0),r=0;t.push(0);for(let s=1;s<=e;s++)n=this.getPoint(s/e),r+=n.distanceTo(i),t.push(r),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const n=this.getLengths();let i=0;const r=n.length;let s;s=t||e*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const u=n[i];return(i+(s-u)/(n[i+1]-u))/(r-1)}getTangent(e,t){const n=1e-4;let i=e-n,r=e+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=t||(s.isVector2?new It:new un);return o.copy(a).sub(s).normalize(),o}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){const n=new un,i=[],r=[],s=[],a=new un,o=new kn;for(let t=0;t<=e;t++){const n=t/e;i[t]=this.getTangentAt(n,new un)}r[0]=new un,s[0]=new un;let l=Number.MAX_VALUE;const u=Math.abs(i[0].x),c=Math.abs(i[0].y),h=Math.abs(i[0].z);u<=l&&(l=u,n.set(1,0,0)),c<=l&&(l=c,n.set(0,1,0)),h<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[0],r[0]);for(let t=1;t<=e;t++){if(r[t]=r[t-1].clone(),s[t]=s[t-1].clone(),a.crossVectors(i[t-1],i[t]),a.length()>Number.EPSILON){a.normalize();const e=Math.acos(Ct(i[t-1].dot(i[t]),-1,1));r[t].applyMatrix4(o.makeRotationAxis(a,e))}s[t].crossVectors(i[t],r[t])}if(!0===t){let t=Math.acos(Ct(r[0].dot(r[e]),-1,1));t/=e,i[0].dot(a.crossVectors(r[0],r[e]))>0&&(t=-t);for(let n=1;n<=e;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],t*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class as extends ss{constructor(e=0,t=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(e,t=new It){const n=t,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===u&&l===r-1&&(l=r-2,u=1),this.closed||l>0?a=i[(l-1)%r]:(ls.subVectors(i[0],i[1]).add(i[0]),a=ls);const c=i[l%r],h=i[(l+1)%r];if(this.closed||l+2i.length-2?i.length-1:s+1],c=i[s>i.length-3?i.length-1:s+2];return n.set(ds(a,o.x,l.x,u.x,c.x),ds(a,o.y,l.y,u.y,c.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t0||0!==i)&&(u.push(s,a,l),v+=3),(t>0||i!==r-1)&&(u.push(a,o,l),v+=3)}l.addGroup(g,v,0),g+=v}(),!1===s&&(e>0&&_(!0),t>0&&_(!1)),this.setIndex(u),this.setAttribute("position",new qi(c,3)),this.setAttribute("normal",new qi(h,3)),this.setAttribute("uv",new qi(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new vs(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class ys extends vs{constructor(e=1,t=1,n=32,i=1,r=!1,s=0,a=2*Math.PI){super(0,e,t,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(e){return new ys(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class xs extends tr{constructor(e=1,t=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};const r=e/2,s=t/2,a=Math.floor(n),o=Math.floor(i),l=a+1,u=o+1,c=e/a,h=t/o,d=[],p=[],f=[],m=[];for(let e=0;e0)&&d.push(t,r,l),(e!==n-1||o0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class ws extends Li{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Pi(16777215),this.specular=new Pi(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pi(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class As extends Li{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Pi(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pi(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class Rs extends Li{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class Cs extends Li{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Pi(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Pi(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Yn,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Ns extends Li{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Ps extends Li{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class Ds extends Li{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Pi(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Us extends qr{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}const Ls={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class Is{constructor(e,t,n){const i=this;let r,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.itemStart=function(e){o++,!1===s&&void 0!==i.onStart&&i.onStart(e,a,o),s=!0},this.itemEnd=function(e){a++,void 0!==i.onProgress&&i.onProgress(e,a,o),a===o&&(s=!1,void 0!==i.onLoad&&i.onLoad())},this.itemError=function(e){void 0!==i.onError&&i.onError(e)},this.resolveURL=function(e){return r?r(e):e},this.setURLModifier=function(e){return r=e,this},this.addHandler=function(e,t){return l.push(e,t),this},this.removeHandler=function(e){const t=l.indexOf(e);return-1!==t&&l.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=l.length;te.start-t.start));let t=0;for(let e=1;e 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"},xa={common:{diffuse:{value:new Pi(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ot},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ot}},envmap:{envMap:{value:null},envMapRotation:{value:new Ot},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ot}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ot}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ot},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ot},normalScale:{value:new It(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ot},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ot}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ot}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ot}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Pi(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Pi(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0},uvTransform:{value:new Ot}},sprite:{diffuse:{value:new Pi(16777215)},opacity:{value:1},center:{value:new It(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ot},alphaMap:{value:null},alphaMapTransform:{value:new Ot},alphaTest:{value:0}}},ba={basic:{uniforms:_r([xa.common,xa.specularmap,xa.envmap,xa.aomap,xa.lightmap,xa.fog]),vertexShader:ya.meshbasic_vert,fragmentShader:ya.meshbasic_frag},lambert:{uniforms:_r([xa.common,xa.specularmap,xa.envmap,xa.aomap,xa.lightmap,xa.emissivemap,xa.bumpmap,xa.normalmap,xa.displacementmap,xa.fog,xa.lights,{emissive:{value:new Pi(0)}}]),vertexShader:ya.meshlambert_vert,fragmentShader:ya.meshlambert_frag},phong:{uniforms:_r([xa.common,xa.specularmap,xa.envmap,xa.aomap,xa.lightmap,xa.emissivemap,xa.bumpmap,xa.normalmap,xa.displacementmap,xa.fog,xa.lights,{emissive:{value:new Pi(0)},specular:{value:new Pi(1118481)},shininess:{value:30}}]),vertexShader:ya.meshphong_vert,fragmentShader:ya.meshphong_frag},standard:{uniforms:_r([xa.common,xa.envmap,xa.aomap,xa.lightmap,xa.emissivemap,xa.bumpmap,xa.normalmap,xa.displacementmap,xa.roughnessmap,xa.metalnessmap,xa.fog,xa.lights,{emissive:{value:new Pi(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ya.meshphysical_vert,fragmentShader:ya.meshphysical_frag},toon:{uniforms:_r([xa.common,xa.aomap,xa.lightmap,xa.emissivemap,xa.bumpmap,xa.normalmap,xa.displacementmap,xa.gradientmap,xa.fog,xa.lights,{emissive:{value:new Pi(0)}}]),vertexShader:ya.meshtoon_vert,fragmentShader:ya.meshtoon_frag},matcap:{uniforms:_r([xa.common,xa.bumpmap,xa.normalmap,xa.displacementmap,xa.fog,{matcap:{value:null}}]),vertexShader:ya.meshmatcap_vert,fragmentShader:ya.meshmatcap_frag},points:{uniforms:_r([xa.points,xa.fog]),vertexShader:ya.points_vert,fragmentShader:ya.points_frag},dashed:{uniforms:_r([xa.common,xa.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ya.linedashed_vert,fragmentShader:ya.linedashed_frag},depth:{uniforms:_r([xa.common,xa.displacementmap]),vertexShader:ya.depth_vert,fragmentShader:ya.depth_frag},normal:{uniforms:_r([xa.common,xa.bumpmap,xa.normalmap,xa.displacementmap,{opacity:{value:1}}]),vertexShader:ya.meshnormal_vert,fragmentShader:ya.meshnormal_frag},sprite:{uniforms:_r([xa.sprite,xa.fog]),vertexShader:ya.sprite_vert,fragmentShader:ya.sprite_frag},background:{uniforms:{uvTransform:{value:new Ot},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ya.background_vert,fragmentShader:ya.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ot}},vertexShader:ya.backgroundCube_vert,fragmentShader:ya.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ya.cube_vert,fragmentShader:ya.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ya.equirect_vert,fragmentShader:ya.equirect_frag},distanceRGBA:{uniforms:_r([xa.common,xa.displacementmap,{referencePosition:{value:new un},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ya.distanceRGBA_vert,fragmentShader:ya.distanceRGBA_frag},shadow:{uniforms:_r([xa.lights,xa.fog,{color:{value:new Pi(0)},opacity:{value:1}}]),vertexShader:ya.shadow_vert,fragmentShader:ya.shadow_frag}};ba.physical={uniforms:_r([ba.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ot},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ot},clearcoatNormalScale:{value:new It(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ot},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ot},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ot},sheen:{value:0},sheenColor:{value:new Pi(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ot},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ot},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ot},transmissionSamplerSize:{value:new It},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ot},attenuationDistance:{value:0},attenuationColor:{value:new Pi(0)},specularColor:{value:new Pi(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ot},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ot},anisotropyVector:{value:new It},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ot}}]),vertexShader:ya.meshphysical_vert,fragmentShader:ya.meshphysical_frag};const Sa={r:0,b:0,g:0},Ta=new Yn,Ma=new kn;function Ea(e,t,n,i,r,s,a){const o=new Pi(0);let l,u,c=!0===s?0:1,h=null,d=0,p=null;function f(e){let i=!0===e.isScene?e.background:null;if(i&&i.isTexture){i=(e.backgroundBlurriness>0?n:t).get(i)}return i}function m(t,n){t.getRGB(Sa,vr(e)),i.buffers.color.setClear(Sa.r,Sa.g,Sa.b,n,a)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),c=t,m(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(e){c=e,m(o,c)},render:function(t){let n=!1;const r=f(t);null===r?m(o,c):r&&r.isColor&&(m(r,1),n=!0);const s=e.xr.getEnvironmentBlendMode();"additive"===s?i.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===s&&i.buffers.color.setClear(0,0,0,0,a),(e.autoClear||n)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,n){const i=f(n);i&&(i.isCubeTexture||i.mapping===X)?(void 0===u&&(u=new pr(new mr(1,1,1),new xr({name:"BackgroundCubeMaterial",uniforms:gr(ba.backgroundCube.uniforms),vertexShader:ba.backgroundCube.vertexShader,fragmentShader:ba.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(u)),Ta.copy(n.backgroundRotation),Ta.x*=-1,Ta.y*=-1,Ta.z*=-1,i.isCubeTexture&&!1===i.isRenderTargetTexture&&(Ta.y*=-1,Ta.z*=-1),u.material.uniforms.envMap.value=i,u.material.uniforms.flipEnvMap.value=i.isCubeTexture&&!1===i.isRenderTargetTexture?-1:1,u.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(Ma.makeRotationFromEuler(Ta)),u.material.toneMapped=Xt.getTransfer(i.colorSpace)!==lt,h===i&&d===i.version&&p===e.toneMapping||(u.material.needsUpdate=!0,h=i,d=i.version,p=e.toneMapping),u.layers.enableAll(),t.unshift(u,u.geometry,u.material,0,0,null)):i&&i.isTexture&&(void 0===l&&(l=new pr(new xs(2,2),new xr({name:"BackgroundMaterial",uniforms:gr(ba.background.uniforms),vertexShader:ba.background.vertexShader,fragmentShader:ba.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.t2D.value=i,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.toneMapped=Xt.getTransfer(i.colorSpace)!==lt,!0===i.matrixAutoUpdate&&i.updateMatrix(),l.material.uniforms.uvTransform.value.copy(i.matrix),h===i&&d===i.version&&p===e.toneMapping||(l.material.needsUpdate=!0,h=i,d=i.version,p=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null))},dispose:function(){void 0!==u&&(u.geometry.dispose(),u.material.dispose(),u=void 0),void 0!==l&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}}}function wa(e,t){const n=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},r=u(null);let s=r,a=!1;function o(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function u(e){const t=[],i=[],r=[];for(let e=0;e=0){const n=r[t];let i=a[t];if(void 0===i&&("instanceMatrix"===t&&e.instanceMatrix&&(i=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(i=e.instanceColor)),void 0===n)return!0;if(n.attribute!==i)return!0;if(i&&n.data!==i.data)return!0;o++}}return s.attributesNum!==o||s.index!==i}(n,m,l,g),_&&function(e,t,n,i){const r={},a=t.attributes;let o=0;const l=n.getAttributes();for(const t in l){if(l[t].location>=0){let n=a[t];void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor));const i={};i.attribute=n,n&&n.data&&(i.data=n.data),r[t]=i,o++}}s.attributes=r,s.attributesNum=o,s.index=i}(n,m,l,g),null!==g&&t.update(g,e.ELEMENT_ARRAY_BUFFER),(_||a)&&(a=!1,function(n,i,r,s){c();const a=s.attributes,o=r.getAttributes(),l=i.defaultAttributeValues;for(const i in o){const r=o[i];if(r.location>=0){let o=a[i];if(void 0===o&&("instanceMatrix"===i&&n.instanceMatrix&&(o=n.instanceMatrix),"instanceColor"===i&&n.instanceColor&&(o=n.instanceColor)),void 0!==o){const i=o.normalized,a=o.itemSize,l=t.get(o);if(void 0===l)continue;const u=l.buffer,c=l.type,p=l.bytesPerElement,m=c===e.INT||c===e.UNSIGNED_INT||o.gpuType===ae;if(o.isInterleavedBufferAttribute){const t=o.data,l=t.stride,g=o.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==n.precision?n.precision:"highp";const o=s(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===n.logarithmicDepthBuffer,u=!0===n.reverseDepthBuffer&&t.has("EXT_clip_control"),c=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");r=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(t){return t===ge||i.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const r=n===ue&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(n!==ne&&i.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==le&&!r)},precision:a,logarithmicDepthBuffer:l,reverseDepthBuffer:u,maxTextures:c,maxVertexTextures:h,maxTextureSize:e.getParameter(e.MAX_TEXTURE_SIZE),maxCubemapSize:e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:e.getParameter(e.MAX_VERTEX_ATTRIBS),maxVertexUniforms:e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:e.getParameter(e.MAX_VARYING_VECTORS),maxFragmentUniforms:e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:h>0,maxSamples:e.getParameter(e.MAX_SAMPLES)}}function Ca(e){const t=this;let n=null,i=0,r=!1,s=!1;const a=new Hr,o=new Ot,l={value:null,needsUpdate:!1};function u(e,n,i,r){const s=null!==e?e.length:0;let u=null;if(0!==s){if(u=l.value,!0!==r||null===u){const t=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===u||u.length0);t.numPlanes=i,t.numIntersection=0}();else{const e=s?0:i,t=4*e;let r=f.clippingState||null;l.value=r,r=u(h,o,t,c);for(let e=0;e!==t;++e)r[e]=n[e];f.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}function Na(e){let t=new WeakMap;function n(e,t){return t===j?e.mapping=V:t===W&&(e.mapping=H),e}function i(e){const n=e.target;n.removeEventListener("dispose",i);const r=t.get(n);void 0!==r&&(t.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping;if(s===j||s===W){if(t.has(r)){return n(t.get(r).texture,r.mapping)}{const s=r.image;if(s&&s.height>0){const a=new Cr(s.height);return a.fromEquirectangularTexture(e,r),t.set(r,a),r.addEventListener("dispose",i),n(a.texture,r.mapping)}return null}}}return r},dispose:function(){t=new WeakMap}}}const Pa=[.125,.215,.35,.446,.526,.582],Da=20,Ua=new Qs,La=new Pi;let Ia=null,Oa=0,Fa=0,Ba=!1;const ka=(1+Math.sqrt(5))/2,za=1/ka,Ga=[new un(-ka,za,0),new un(ka,za,0),new un(-za,0,ka),new un(za,0,ka),new un(0,ka,-za),new un(0,ka,za),new un(-1,1,-1),new un(1,1,-1),new un(-1,1,1),new un(1,1,1)],Va=new un;let Ha=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,i=100,r={}){const{size:s=256,position:a=Va}=r;Ia=this._renderer.getRenderTarget(),Oa=this._renderer.getActiveCubeFace(),Fa=this._renderer.getActiveMipmapLevel(),Ba=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);const o=this._allocateTargets();return o.depthBuffer=!0,this._sceneToCubeUV(e,n,i,o,a),t>0&&this._blur(o,0,0,t),this._applyPMREM(o),this._cleanup(o),o}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=qa(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Xa(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?o=Pa[a-e+4-1]:0===a&&(o=0),i.push(o);const l=1/(s-2),u=-l,c=1+l,h=[u,u,c,u,c,c,u,u,c,c,u,c],d=6,p=6,f=3,m=2,g=1,_=new Float32Array(f*p*d),v=new Float32Array(m*p*d),y=new Float32Array(g*p*d);for(let e=0;e2?0:-1,i=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];_.set(i,f*p*e),v.set(h,m*p*e);const r=[e,e,e,e,e,e];y.set(r,g*p*e)}const x=new tr;x.setAttribute("position",new Hi(_,f)),x.setAttribute("uv",new Hi(v,m)),x.setAttribute("faceIndex",new Hi(y,g)),t.push(x),r>4&&r--}return{lodPlanes:t,sizeLods:n,sigmas:i}}(i)),this._blurMaterial=function(e,t,n){const i=new Float32Array(Da),r=new un(0,1,0),s=new xr({name:"SphericalGaussianBlur",defines:{n:Da,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:$a(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1});return s}(i,e,t)}return i}_compileMaterial(e){const t=new pr(this._lodPlanes[0],e);this._renderer.compile(t,Ua)}_sceneToCubeUV(e,t,n,i,r){const s=new Er(90,1,t,n),a=[1,-1,1,1,1,1],o=[1,1,1,-1,-1,-1],l=this._renderer,u=l.autoClear,c=l.toneMapping;l.getClearColor(La),l.toneMapping=0,l.autoClear=!1;const h=new Ii({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),d=new pr(new mr,h);let p=!1;const f=e.background;f?f.isColor&&(h.color.copy(f),e.background=null,p=!0):(h.color.copy(La),p=!0);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x+o[t],r.y,r.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y+o[t],r.z)):(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y,r.z+o[t]));const u=this._cubeSize;Wa(i,n*u,t>2?u:0,u,u),l.setRenderTarget(i),p&&l.render(d,s),l.render(e,s)}d.geometry.dispose(),d.material.dispose(),l.toneMapping=c,l.autoClear=u,e.background=f}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===V||e.mapping===H;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=qa()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Xa());const r=i?this._cubemapMaterial:this._equirectMaterial,s=new pr(this._lodPlanes[0],r);r.uniforms.envMap.value=e;const a=this._cubeSize;Wa(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,Ua)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let t=1;tDa&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let e=0;e_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,Ua)}};function ja(e,t,n){const i=new sn(e,t,n);return i.texture.mapping=X,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Wa(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function Xa(){return new xr({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:$a(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function qa(){return new xr({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:$a(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function $a(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function Ya(e){let t=new WeakMap,n=null;function i(e){const n=e.target;n.removeEventListener("dispose",i);const r=t.get(n);void 0!==r&&(t.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping,a=s===j||s===W,o=s===V||s===H;if(a||o){let s=t.get(r);const l=void 0!==s?s.texture.pmremVersion:0;if(r.isRenderTargetTexture&&r.pmremVersion!==l)return null===n&&(n=new Ha(e)),s=a?n.fromEquirectangular(r,s):n.fromCubemap(r,s),s.texture.pmremVersion=r.pmremVersion,t.set(r,s),s.texture;if(void 0!==s)return s.texture;{const l=r.image;return a&&l&&l.height>0||o&&l&&function(e){let t=0;const n=6;for(let i=0;it.maxTextureSize&&(x=Math.ceil(y/t.maxTextureSize),y=t.maxTextureSize);const b=new Float32Array(y*x*4*c),S=new an(b,y,x,c);S.type=le,S.needsUpdate=!0;const T=4*v;for(let E=0;E0)return e;const r=t*n;let s=oo[r];if(void 0===s&&(s=new Float32Array(r),oo[r]=s),0!==t){i.toArray(s,0);for(let i=1,r=0;i!==t;++i)r+=n,e[i].toArray(s,r)}return s}function fo(e,t){if(e.length!==t.length)return!1;for(let n=0,i=e.length;n":" "} ${r}: ${n[e]}`)}return i.join("\n")}(e.getShaderSource(t),i)}return r}function dl(e,t){const n=function(e){Xt._getMatrix(cl,Xt.workingColorSpace,e);const t=`mat3( ${cl.elements.map((e=>e.toFixed(4)))} )`;switch(Xt.getTransfer(e)){case ot:return[t,"LinearTransferOETF"];case lt:return[t,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}(t);return[`vec4 ${e}( vec4 value ) {`,`\treturn ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join("\n")}function pl(e,t){let n;switch(t){case 1:n="Linear";break;case 2:n="Reinhard";break;case 3:n="Cineon";break;case 4:n="ACESFilmic";break;case 6:n="AgX";break;case 7:n="Neutral";break;case 5:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),n="Linear"}return"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const fl=new un;function ml(){Xt.getLuminanceCoefficients(fl);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${fl.x.toFixed(4)}, ${fl.y.toFixed(4)}, ${fl.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function gl(e){return""!==e}function _l(e,t){const n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function vl(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const yl=/^[ \t]*#include +<([\w\d./]+)>/gm;function xl(e){return e.replace(yl,Sl)}const bl=new Map;function Sl(e,t){let n=ya[t];if(void 0===n){const e=bl.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=ya[e],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return xl(n)}const Tl=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Ml(e){return e.replace(Tl,El)}function El(e,t,n,i){let r="";for(let e=parseInt(t);e0&&(g+="\n"),_=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(gl).join("\n"),_.length>0&&(_+="\n")):(g=[wl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+c:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(gl).join("\n"),_=[wl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.envMap?"#define "+c:"",n.envMap?"#define "+h:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?ya.tonemapping_pars_fragment:"",0!==n.toneMapping?pl("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",ya.colorspace_pars_fragment,dl("linearToOutputTexel",n.outputColorSpace),ml(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(gl).join("\n")),a=xl(a),a=_l(a,n),a=vl(a,n),o=xl(o),o=_l(o,n),o=vl(o,n),a=Ml(a),o=Ml(o),!0!==n.isRawShaderMaterial&&(v="#version 300 es\n",g=[p,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,_=["#define varying in",n.glslVersion===xt?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===xt?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+_);const y=v+g+a,x=v+_+o,b=ll(r,r.VERTEX_SHADER,y),S=ll(r,r.FRAGMENT_SHADER,x);function T(t){if(e.debug.checkShaderErrors){const n=r.getProgramInfoLog(m).trim(),i=r.getShaderInfoLog(b).trim(),s=r.getShaderInfoLog(S).trim();let a=!0,o=!0;if(!1===r.getProgramParameter(m,r.LINK_STATUS))if(a=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(r,m,b,S);else{const e=hl(r,b,"vertex"),i=hl(r,S,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(m,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+n+"\n"+e+"\n"+i)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==i&&""!==s||(o=!1);o&&(t.diagnostics={runnable:a,programLog:n,vertexShader:{log:i,prefix:g},fragmentShader:{log:s,prefix:_}})}r.deleteShader(b),r.deleteShader(S),M=new ol(r,m),E=function(e,t){const n={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r0,$=s.clearcoat>0,Y=s.dispersion>0,K=s.iridescence>0,Z=s.sheen>0,Q=s.transmission>0,J=q&&!!s.anisotropyMap,ee=$&&!!s.clearcoatMap,te=$&&!!s.clearcoatNormalMap,ne=$&&!!s.clearcoatRoughnessMap,ie=K&&!!s.iridescenceMap,re=K&&!!s.iridescenceThicknessMap,se=Z&&!!s.sheenColorMap,ae=Z&&!!s.sheenRoughnessMap,oe=!!s.specularMap,le=!!s.specularColorMap,ue=!!s.specularIntensityMap,ce=Q&&!!s.transmissionMap,he=Q&&!!s.thicknessMap,de=!!s.gradientMap,pe=!!s.alphaMap,fe=s.alphaTest>0,me=!!s.alphaHash,ge=!!s.extensions;let _e=0;s.toneMapped&&(null!==P&&!0!==P.isXRRenderTarget||(_e=e.toneMapping));const ve={shaderID:T,shaderType:s.type,shaderName:s.name,vertexShader:w,fragmentShader:A,defines:s.defines,customVertexShaderID:R,customFragmentShaderID:C,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:p,batching:L,batchingColor:L&&null!==_._colorsTexture,instancing:U,instancingColor:U&&null!==_.instanceColor,instancingMorph:U&&null!==_.morphTexture,supportsVertexTextures:d,outputColorSpace:null===P?e.outputColorSpace:!0===P.isXRRenderTarget?P.texture.colorSpace:at,alphaToCoverage:!!s.alphaToCoverage,map:I,matcap:O,envMap:F,envMapMode:F&&b.mapping,envMapCubeUVHeight:S,aoMap:B,lightMap:k,bumpMap:z,normalMap:G,displacementMap:d&&V,emissiveMap:H,normalMapObjectSpace:G&&1===s.normalMapType,normalMapTangentSpace:G&&0===s.normalMapType,metalnessMap:j,roughnessMap:W,anisotropy:q,anisotropyMap:J,clearcoat:$,clearcoatMap:ee,clearcoatNormalMap:te,clearcoatRoughnessMap:ne,dispersion:Y,iridescence:K,iridescenceMap:ie,iridescenceThicknessMap:re,sheen:Z,sheenColorMap:se,sheenRoughnessMap:ae,specularMap:oe,specularColorMap:le,specularIntensityMap:ue,transmission:Q,transmissionMap:ce,thicknessMap:he,gradientMap:de,opaque:!1===s.transparent&&1===s.blending&&!1===s.alphaToCoverage,alphaMap:pe,alphaTest:fe,alphaHash:me,combine:s.combine,mapUv:I&&m(s.map.channel),aoMapUv:B&&m(s.aoMap.channel),lightMapUv:k&&m(s.lightMap.channel),bumpMapUv:z&&m(s.bumpMap.channel),normalMapUv:G&&m(s.normalMap.channel),displacementMapUv:V&&m(s.displacementMap.channel),emissiveMapUv:H&&m(s.emissiveMap.channel),metalnessMapUv:j&&m(s.metalnessMap.channel),roughnessMapUv:W&&m(s.roughnessMap.channel),anisotropyMapUv:J&&m(s.anisotropyMap.channel),clearcoatMapUv:ee&&m(s.clearcoatMap.channel),clearcoatNormalMapUv:te&&m(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ne&&m(s.clearcoatRoughnessMap.channel),iridescenceMapUv:ie&&m(s.iridescenceMap.channel),iridescenceThicknessMapUv:re&&m(s.iridescenceThicknessMap.channel),sheenColorMapUv:se&&m(s.sheenColorMap.channel),sheenRoughnessMapUv:ae&&m(s.sheenRoughnessMap.channel),specularMapUv:oe&&m(s.specularMap.channel),specularColorMapUv:le&&m(s.specularColorMap.channel),specularIntensityMapUv:ue&&m(s.specularIntensityMap.channel),transmissionMapUv:ce&&m(s.transmissionMap.channel),thicknessMapUv:he&&m(s.thicknessMap.channel),alphaMapUv:pe&&m(s.alphaMap.channel),vertexTangents:!!y.attributes.tangent&&(G||q),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!y.attributes.color&&4===y.attributes.color.itemSize,pointsUvs:!0===_.isPoints&&!!y.attributes.uv&&(I||pe),fog:!!v,useFog:!0===s.fog,fogExp2:!!v&&v.isFogExp2,flatShading:!0===s.flatShading,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:h,reverseDepthBuffer:D,skinning:!0===_.isSkinnedMesh,morphTargets:void 0!==y.morphAttributes.position,morphNormals:void 0!==y.morphAttributes.normal,morphColors:void 0!==y.morphAttributes.color,morphTargetsCount:E,morphTextureStride:N,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:e.shadowMap.enabled&&c.length>0,shadowMapType:e.shadowMap.type,toneMapping:_e,decodeVideoTexture:I&&!0===s.map.isVideoTexture&&Xt.getTransfer(s.map.colorSpace)===lt,decodeVideoTextureEmissive:H&&!0===s.emissiveMap.isVideoTexture&&Xt.getTransfer(s.emissiveMap.colorSpace)===lt,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:1===s.side,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionClipCullDistance:ge&&!0===s.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ge&&!0===s.extensions.multiDraw||L)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return ve.vertexUv1s=u.has(1),ve.vertexUv2s=u.has(2),ve.vertexUv3s=u.has(3),u.clear(),ve},getProgramCacheKey:function(t){const n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)n.push(e),n.push(t.defines[e]);return!1===t.isRawShaderMaterial&&(!function(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}(n,t),function(e,t){o.disableAll(),t.supportsVertexTextures&&o.enable(0);t.instancing&&o.enable(1);t.instancingColor&&o.enable(2);t.instancingMorph&&o.enable(3);t.matcap&&o.enable(4);t.envMap&&o.enable(5);t.normalMapObjectSpace&&o.enable(6);t.normalMapTangentSpace&&o.enable(7);t.clearcoat&&o.enable(8);t.iridescence&&o.enable(9);t.alphaTest&&o.enable(10);t.vertexColors&&o.enable(11);t.vertexAlphas&&o.enable(12);t.vertexUv1s&&o.enable(13);t.vertexUv2s&&o.enable(14);t.vertexUv3s&&o.enable(15);t.vertexTangents&&o.enable(16);t.anisotropy&&o.enable(17);t.alphaHash&&o.enable(18);t.batching&&o.enable(19);t.dispersion&&o.enable(20);t.batchingColor&&o.enable(21);e.push(o.mask),o.disableAll(),t.fog&&o.enable(0);t.useFog&&o.enable(1);t.flatShading&&o.enable(2);t.logarithmicDepthBuffer&&o.enable(3);t.reverseDepthBuffer&&o.enable(4);t.skinning&&o.enable(5);t.morphTargets&&o.enable(6);t.morphNormals&&o.enable(7);t.morphColors&&o.enable(8);t.premultipliedAlpha&&o.enable(9);t.shadowMapEnabled&&o.enable(10);t.doubleSided&&o.enable(11);t.flipSided&&o.enable(12);t.useDepthPacking&&o.enable(13);t.dithering&&o.enable(14);t.transmission&&o.enable(15);t.sheen&&o.enable(16);t.opaque&&o.enable(17);t.pointsUvs&&o.enable(18);t.decodeVideoTexture&&o.enable(19);t.decodeVideoTextureEmissive&&o.enable(20);t.alphaToCoverage&&o.enable(21);e.push(o.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){const t=f[e.type];let n;if(t){const e=ba[t];n=yr.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let i;for(let e=0,t=c.length;e0?i.push(c):!0===a.transparent?r.push(c):n.push(c)},unshift:function(e,t,a,o,l,u){const c=s(e,t,a,o,l,u);a.transmission>0?i.unshift(c):!0===a.transparent?r.unshift(c):n.unshift(c)},finish:function(){for(let n=t,i=e.length;n1&&n.sort(e||Ul),i.length>1&&i.sort(t||Ll),r.length>1&&r.sort(t||Ll)}}}function Ol(){let e=new WeakMap;return{get:function(t,n){const i=e.get(t);let r;return void 0===i?(r=new Il,e.set(t,[r])):n>=i.length?(r=new Il,i.push(r)):r=i[n],r},dispose:function(){e=new WeakMap}}}function Fl(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":n={direction:new un,color:new Pi};break;case"SpotLight":n={position:new un,direction:new un,color:new Pi,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new un,color:new Pi,distance:0,decay:0};break;case"HemisphereLight":n={direction:new un,skyColor:new Pi,groundColor:new Pi};break;case"RectAreaLight":n={color:new Pi,position:new un,halfWidth:new un,halfHeight:new un}}return e[t.id]=n,n}}}let Bl=0;function kl(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function zl(e){const t=new Fl,n=function(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new It};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new It,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)i.probe.push(new un);const r=new un,s=new kn,a=new kn;return{setup:function(r){let s=0,a=0,o=0;for(let e=0;e<9;e++)i.probe[e].set(0,0,0);let l=0,u=0,c=0,h=0,d=0,p=0,f=0,m=0,g=0,_=0,v=0;r.sort(kl);for(let e=0,y=r.length;e0&&(!0===e.has("OES_texture_float_linear")?(i.rectAreaLTC1=xa.LTC_FLOAT_1,i.rectAreaLTC2=xa.LTC_FLOAT_2):(i.rectAreaLTC1=xa.LTC_HALF_1,i.rectAreaLTC2=xa.LTC_HALF_2)),i.ambient[0]=s,i.ambient[1]=a,i.ambient[2]=o;const y=i.hash;y.directionalLength===l&&y.pointLength===u&&y.spotLength===c&&y.rectAreaLength===h&&y.hemiLength===d&&y.numDirectionalShadows===p&&y.numPointShadows===f&&y.numSpotShadows===m&&y.numSpotMaps===g&&y.numLightProbes===v||(i.directional.length=l,i.spot.length=c,i.rectArea.length=h,i.point.length=u,i.hemi.length=d,i.directionalShadow.length=p,i.directionalShadowMap.length=p,i.pointShadow.length=f,i.pointShadowMap.length=f,i.spotShadow.length=m,i.spotShadowMap.length=m,i.directionalShadowMatrix.length=p,i.pointShadowMatrix.length=f,i.spotLightMatrix.length=m+g-_,i.spotLightMap.length=g,i.numSpotLightShadowsWithMaps=_,i.numLightProbes=v,y.directionalLength=l,y.pointLength=u,y.spotLength=c,y.rectAreaLength=h,y.hemiLength=d,y.numDirectionalShadows=p,y.numPointShadows=f,y.numSpotShadows=m,y.numSpotMaps=g,y.numLightProbes=v,i.version=Bl++)},setupView:function(e,t){let n=0,o=0,l=0,u=0,c=0;const h=t.matrixWorldInverse;for(let t=0,d=e.length;t=r.length?(s=new Gl(e),r.push(s)):s=r[i],s},dispose:function(){t=new WeakMap}}}function Hl(e,t,n){let i=new Xr;const r=new It,s=new It,a=new nn,o=new Ns({depthPacking:3201}),l=new Ps,u={},c=n.maxTextureSize,h={[p]:1,[f]:0,[m]:2},d=new xr({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new It},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),g=d.clone();g.defines.HORIZONTAL_PASS=1;const _=new tr;_.setAttribute("position",new Hi(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new pr(_,d),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let x=this.type;function b(n,i){const s=t.update(v);d.defines.VSM_SAMPLES!==n.blurSamples&&(d.defines.VSM_SAMPLES=n.blurSamples,g.defines.VSM_SAMPLES=n.blurSamples,d.needsUpdate=!0,g.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new sn(r.x,r.y)),d.uniforms.shadow_pass.value=n.map.texture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(i,null,s,d,v,null),g.uniforms.shadow_pass.value=n.mapPass.texture,g.uniforms.resolution.value=n.mapSize,g.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(i,null,s,g,v,null)}function S(t,n,i,r){let s=null;const a=!0===i.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?l:o,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0){const e=s.uuid,t=n.uuid;let i=u[e];void 0===i&&(i={},u[e]=i);let r=i[t];void 0===r&&(r=s.clone(),i[t]=r,n.addEventListener("dispose",M)),s=r}if(s.visible=n.visible,s.wireframe=n.wireframe,s.side=3===r?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:h[n.side],s.alphaMap=n.alphaMap,s.alphaTest=n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===i.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=i}return s}function T(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=t.update(n),l=n.material;if(Array.isArray(l)){const t=i.groups;for(let u=0,c=t.length;uc||r.y>c)&&(r.x>c&&(s.x=Math.floor(c/m.x),r.x=s.x*m.x,h.mapSize.x=s.x),r.y>c&&(s.y=Math.floor(c/m.y),r.y=s.y*m.y,h.mapSize.y=s.y)),null===h.map||!0===p||!0===f){const e=3!==this.type?{minFilter:K,magFilter:K}:{};null!==h.map&&h.map.dispose(),h.map=new sn(r.x,r.y,e),h.map.texture.name=u.name+".shadowMap",h.camera.updateProjectionMatrix()}e.setRenderTarget(h.map),e.clear();const g=h.getViewportCount();for(let e=0;e=1):-1!==Y.indexOf("OpenGL ES")&&($=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),q=$>=2);let K=null,Z={};const Q=e.getParameter(e.SCISSOR_BOX),J=e.getParameter(e.VIEWPORT),ee=(new nn).fromArray(Q),te=(new nn).fromArray(J);function ne(t,n,i,r){const s=new Uint8Array(4),a=e.createTexture();e.bindTexture(t,a),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let a=0;an||r.height>n)&&(i=n/Math.max(r.width,r.height)),i<1){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&e instanceof VideoFrame){const n=Math.floor(i*r.width),s=Math.floor(i*r.height);void 0===h&&(h=f(n,s));const a=t?f(n,s):h;a.width=n,a.height=s;return a.getContext("2d").drawImage(e,0,0,n,s),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+r.width+"x"+r.height+") to ("+n+"x"+s+")."),a}return"data"in e&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.height+")."),e}return e}function g(e){return e.generateMipmaps}function _(t){e.generateMipmap(t)}function v(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function y(n,i,r,s,a=!1){if(null!==n){if(void 0!==e[n])return e[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let o=i;if(i===e.RED&&(r===e.FLOAT&&(o=e.R32F),r===e.HALF_FLOAT&&(o=e.R16F),r===e.UNSIGNED_BYTE&&(o=e.R8)),i===e.RED_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.R8UI),r===e.UNSIGNED_SHORT&&(o=e.R16UI),r===e.UNSIGNED_INT&&(o=e.R32UI),r===e.BYTE&&(o=e.R8I),r===e.SHORT&&(o=e.R16I),r===e.INT&&(o=e.R32I)),i===e.RG&&(r===e.FLOAT&&(o=e.RG32F),r===e.HALF_FLOAT&&(o=e.RG16F),r===e.UNSIGNED_BYTE&&(o=e.RG8)),i===e.RG_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RG8UI),r===e.UNSIGNED_SHORT&&(o=e.RG16UI),r===e.UNSIGNED_INT&&(o=e.RG32UI),r===e.BYTE&&(o=e.RG8I),r===e.SHORT&&(o=e.RG16I),r===e.INT&&(o=e.RG32I)),i===e.RGB_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGB8UI),r===e.UNSIGNED_SHORT&&(o=e.RGB16UI),r===e.UNSIGNED_INT&&(o=e.RGB32UI),r===e.BYTE&&(o=e.RGB8I),r===e.SHORT&&(o=e.RGB16I),r===e.INT&&(o=e.RGB32I)),i===e.RGBA_INTEGER&&(r===e.UNSIGNED_BYTE&&(o=e.RGBA8UI),r===e.UNSIGNED_SHORT&&(o=e.RGBA16UI),r===e.UNSIGNED_INT&&(o=e.RGBA32UI),r===e.BYTE&&(o=e.RGBA8I),r===e.SHORT&&(o=e.RGBA16I),r===e.INT&&(o=e.RGBA32I)),i===e.RGB&&r===e.UNSIGNED_INT_5_9_9_9_REV&&(o=e.RGB9_E5),i===e.RGBA){const t=a?ot:Xt.getTransfer(s);r===e.FLOAT&&(o=e.RGBA32F),r===e.HALF_FLOAT&&(o=e.RGBA16F),r===e.UNSIGNED_BYTE&&(o=t===lt?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)}return o!==e.R16F&&o!==e.R32F&&o!==e.RG16F&&o!==e.RG32F&&o!==e.RGBA16F&&o!==e.RGBA32F||t.get("EXT_color_buffer_float"),o}function x(t,n){let i;return t?null===n||n===oe||n===de?i=e.DEPTH24_STENCIL8:n===le?i=e.DEPTH32F_STENCIL8:n===se&&(i=e.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===oe||n===de?i=e.DEPTH_COMPONENT24:n===le?i=e.DEPTH_COMPONENT32F:n===se&&(i=e.DEPTH_COMPONENT16),i}function b(e,t){return!0===g(e)||e.isFramebufferTexture&&e.minFilter!==K&&e.minFilter!==J?Math.log2(Math.max(t.width,t.height))+1:void 0!==e.mipmaps&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function S(e){const t=e.target;t.removeEventListener("dispose",S),function(e){const t=i.get(e);if(void 0===t.__webglInit)return;const n=e.source,r=d.get(n);if(r){const i=r[t.__cacheKey];i.usedTimes--,0===i.usedTimes&&M(e),0===Object.keys(r).length&&d.delete(n)}i.remove(e)}(t),t.isVideoTexture&&c.delete(t)}function T(t){const n=t.target;n.removeEventListener("dispose",T),function(t){const n=i.get(t);t.depthTexture&&(t.depthTexture.dispose(),i.remove(t.depthTexture));if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let i=0;i0&&s.__version!==t.version){const e=t.image;if(null===e)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void D(s,t,r);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+r)}const A={[q]:e.REPEAT,[$]:e.CLAMP_TO_EDGE,[Y]:e.MIRRORED_REPEAT},R={[K]:e.NEAREST,[Z]:e.NEAREST_MIPMAP_NEAREST,[Q]:e.NEAREST_MIPMAP_LINEAR,[J]:e.LINEAR,[ee]:e.LINEAR_MIPMAP_NEAREST,[te]:e.LINEAR_MIPMAP_LINEAR},C={[ct]:e.NEVER,[_t]:e.ALWAYS,[ht]:e.LESS,[pt]:e.LEQUAL,[dt]:e.EQUAL,[gt]:e.GEQUAL,[ft]:e.GREATER,[mt]:e.NOTEQUAL};function N(n,s){if(s.type!==le||!1!==t.has("OES_texture_float_linear")||s.magFilter!==J&&s.magFilter!==ee&&s.magFilter!==Q&&s.magFilter!==te&&s.minFilter!==J&&s.minFilter!==ee&&s.minFilter!==Q&&s.minFilter!==te||console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(n,e.TEXTURE_WRAP_S,A[s.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,A[s.wrapT]),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,A[s.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,R[s.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,R[s.minFilter]),s.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,C[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(s.magFilter===K)return;if(s.minFilter!==Q&&s.minFilter!==te)return;if(s.type===le&&!1===t.has("OES_texture_float_linear"))return;if(s.anisotropy>1||i.get(s).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy}}}function P(t,n){let i=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",S));const r=n.source;let s=d.get(r);void 0===s&&(s={},d.set(r,s));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(n);if(o!==t.__cacheKey){void 0===s[o]&&(s[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[t.__cacheKey];void 0!==r&&(s[t.__cacheKey].usedTimes--,0===r.usedTimes&&M(n)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return i}function D(t,a,o){let l=e.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=e.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=e.TEXTURE_3D);const u=P(t,a),c=a.source;n.bindTexture(l,t.__webglTexture,e.TEXTURE0+o);const h=i.get(c);if(c.version!==h.__version||!0===u){n.activeTexture(e.TEXTURE0+o);const t=Xt.getPrimaries(Xt.workingColorSpace),i=a.colorSpace===rt?null:Xt.getPrimaries(a.colorSpace),d=a.colorSpace===rt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let p=m(a.image,!1,r.maxTextureSize);p=z(a,p);const f=s.convert(a.format,a.colorSpace),v=s.convert(a.type);let S,T=y(a.internalFormat,f,v,a.colorSpace,a.isVideoTexture);N(l,a);const M=a.mipmaps,E=!0!==a.isVideoTexture,w=void 0===h.__version||!0===u,A=c.dataReady,R=b(a,p);if(a.isDepthTexture)T=x(a.format===xe,a.type),w&&(E?n.texStorage2D(e.TEXTURE_2D,1,T,p.width,p.height):n.texImage2D(e.TEXTURE_2D,0,T,p.width,p.height,0,f,v,null));else if(a.isDataTexture)if(M.length>0){E&&w&&n.texStorage2D(e.TEXTURE_2D,R,T,M[0].width,M[0].height);for(let t=0,i=M.length;t0){const i=ga(S.width,S.height,a.format,a.type);for(const r of a.layerUpdates){const s=S.data.subarray(r*i/S.data.BYTES_PER_ELEMENT,(r+1)*i/S.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,r,S.width,S.height,1,f,s)}a.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,S.width,S.height,p.depth,f,S.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,T,S.width,S.height,p.depth,0,S.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else E?A&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,S.width,S.height,p.depth,f,v,S.data):n.texImage3D(e.TEXTURE_2D_ARRAY,t,T,S.width,S.height,p.depth,0,f,v,S.data)}else{E&&w&&n.texStorage2D(e.TEXTURE_2D,R,T,M[0].width,M[0].height);for(let t=0,i=M.length;t0){const t=ga(p.width,p.height,a.format,a.type);for(const i of a.layerUpdates){const r=p.data.subarray(i*t/p.data.BYTES_PER_ELEMENT,(i+1)*t/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,i,p.width,p.height,1,f,v,r)}a.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,T,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isData3DTexture)E?(w&&n.texStorage3D(e.TEXTURE_3D,R,T,p.width,p.height,p.depth),A&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)):n.texImage3D(e.TEXTURE_3D,0,T,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isFramebufferTexture){if(w)if(E)n.texStorage2D(e.TEXTURE_2D,R,T,p.width,p.height);else{let t=p.width,i=p.height;for(let r=0;r>=1,i>>=1}}else if(M.length>0){if(E&&w){const t=G(M[0]);n.texStorage2D(e.TEXTURE_2D,R,T,t.width,t.height)}for(let t=0,i=M.length;t>c),i=Math.max(1,r.height>>c);u===e.TEXTURE_3D||u===e.TEXTURE_2D_ARRAY?n.texImage3D(u,c,p,t,i,r.depth,0,h,d,null):n.texImage2D(u,c,p,t,i,0,h,d,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),k(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,u,m.__webglTexture,0,B(r)):(u===e.TEXTURE_2D||u>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&u<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,l,u,m.__webglTexture,c),n.bindFramebuffer(e.FRAMEBUFFER,null)}function L(t,n,i){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){const r=n.depthTexture,s=r&&r.isDepthTexture?r.type:null,a=x(n.stencilBuffer,s),l=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=B(n);k(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,u,a,n.width,n.height):i?e.renderbufferStorageMultisample(e.RENDERBUFFER,u,a,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,a,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,l,e.RENDERBUFFER,t)}else{const t=n.textures;for(let r=0;r{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),r.__depthDisposeCallback=t}r.__boundDepthTexture=e}if(t.depthTexture&&!r.__autoAllocateDepthBuffer){if(s)throw new Error("target.depthTexture not supported in Cube render targets");!function(t,r){if(r&&r.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(e.FRAMEBUFFER,t),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const s=i.get(r.depthTexture);s.__renderTarget=r,s.__webglTexture&&r.depthTexture.image.width===r.width&&r.depthTexture.image.height===r.height||(r.depthTexture.image.width=r.width,r.depthTexture.image.height=r.height,r.depthTexture.needsUpdate=!0),w(r.depthTexture,0);const a=s.__webglTexture,l=B(r);if(r.depthTexture.format===ye)k(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0,l):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0);else{if(r.depthTexture.format!==xe)throw new Error("Unknown depthTexture format");k(r)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,a,0,l):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,a,0)}}(r.__webglFramebuffer,t)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer[i]),void 0===r.__webglDepthbuffer[i])r.__webglDepthbuffer[i]=e.createRenderbuffer(),L(r.__webglDepthbuffer[i],t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[i];e.bindRenderbuffer(e.RENDERBUFFER,s),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,s)}}else if(n.bindFramebuffer(e.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=e.createRenderbuffer(),L(r.__webglDepthbuffer,t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,i=r.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,i),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,i)}n.bindFramebuffer(e.FRAMEBUFFER,null)}const O=[],F=[];function B(e){return Math.min(r.maxSamples,e.samples)}function k(e){const n=i.get(e);return e.samples>0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function z(e,t){const n=e.colorSpace,i=e.format,r=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||n!==at&&n!==rt&&(Xt.getTransfer(n)===lt?i===ge&&r===ne||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",n)),t}function G(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement?(u.width=e.naturalWidth||e.width,u.height=e.naturalHeight||e.height):"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?(u.width=e.displayWidth,u.height=e.displayHeight):(u.width=e.width,u.height=e.height),u}this.allocateTextureUnit=function(){const e=E;return e>=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+r.maxTextures),E+=1,e},this.resetTextureUnits=function(){E=0},this.setTexture2D=w,this.setTexture2DArray=function(t,r){const s=i.get(t);t.version>0&&s.__version!==t.version?D(s,t,r):n.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+r)},this.setTexture3D=function(t,r){const s=i.get(t);t.version>0&&s.__version!==t.version?D(s,t,r):n.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+r)},this.setTextureCube=function(t,a){const o=i.get(t);t.version>0&&o.__version!==t.version?function(t,a,o){if(6!==a.image.length)return;const l=P(t,a),u=a.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+o);const c=i.get(u);if(u.version!==c.__version||!0===l){n.activeTexture(e.TEXTURE0+o);const t=Xt.getPrimaries(Xt.workingColorSpace),i=a.colorSpace===rt?null:Xt.getPrimaries(a.colorSpace),h=a.colorSpace===rt||t===i?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,h);const d=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,f=[];for(let e=0;e<6;e++)f[e]=d||p?p?a.image[e].image:a.image[e]:m(a.image[e],!0,r.maxCubemapSize),f[e]=z(a,f[e]);const v=f[0],x=s.convert(a.format,a.colorSpace),S=s.convert(a.type),T=y(a.internalFormat,x,S,a.colorSpace),M=!0!==a.isVideoTexture,E=void 0===c.__version||!0===l,w=u.dataReady;let A,R=b(a,v);if(N(e.TEXTURE_CUBE_MAP,a),d){M&&E&&n.texStorage2D(e.TEXTURE_CUBE_MAP,R,T,v.width,v.height);for(let t=0;t<6;t++){A=f[t].mipmaps;for(let i=0;i0&&R++;const t=G(f[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,R,T,t.width,t.height)}for(let t=0;t<6;t++)if(p){M?w&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,f[t].width,f[t].height,x,S,f[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,T,f[t].width,f[t].height,0,x,S,f[t].data);for(let i=0;i1;if(h||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=r.version,a.memory.textures++),c){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let n=0;n0){o.__webglFramebuffer=[];for(let t=0;t0&&!1===k(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n0)for(let i=0;i0)for(let n=0;n0)if(!1===k(t)){const r=t.textures,s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const u=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,c=i.get(t),h=r.length>1;if(h)for(let t=0;t= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new pr(new xs(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Yl extends Tt{constructor(e,t){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,u=null,c=null,h=null,d=null,p=null;const f=new $l,m=t.getContextAttributes();let g=null,_=null;const v=[],y=[],x=new It;let b=null;const S=new Er;S.viewport=new nn;const T=new Er;T.viewport=new nn;const M=[S,T],E=new sa;let w=null,A=null;function R(e){const t=y.indexOf(e.inputSource);if(-1===t)return;const n=v[t];void 0!==n&&(n.update(e.inputSource,e.frame,l||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function C(){i.removeEventListener("select",R),i.removeEventListener("selectstart",R),i.removeEventListener("selectend",R),i.removeEventListener("squeeze",R),i.removeEventListener("squeezestart",R),i.removeEventListener("squeezeend",R),i.removeEventListener("end",C),i.removeEventListener("inputsourceschange",N);for(let e=0;e=0&&(y[i]=null,v[i].disconnect(n))}for(let t=0;t=y.length){y.push(n),i=e;break}if(null===y[e]){y[e]=n,i=e;break}}if(-1===i)break}const r=v[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=v[e];return void 0===t&&(t=new Dr,v[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=v[e];return void 0===t&&(t=new Dr,v[e]=t),t.getGripSpace()},this.getHand=function(e){let t=v[e];return void 0===t&&(t=new Dr,v[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){r=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(e){l=e},this.getBaseLayer=function(){return null!==h?h:d},this.getBinding=function(){return c},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(u){if(i=u,null!==i){g=e.getRenderTarget(),i.addEventListener("select",R),i.addEventListener("selectstart",R),i.addEventListener("selectend",R),i.addEventListener("squeeze",R),i.addEventListener("squeezestart",R),i.addEventListener("squeezeend",R),i.addEventListener("end",C),i.addEventListener("inputsourceschange",N),!0!==m.xrCompatible&&await t.makeXRCompatible(),b=e.getPixelRatio(),e.getSize(x);if("undefined"!=typeof XRWebGLBinding&&"createProjectionLayer"in XRWebGLBinding.prototype){let n=null,s=null,a=null;m.depth&&(a=m.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=m.stencil?xe:ye,s=m.stencil?de:oe);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:r};c=new XRWebGLBinding(i,t),h=c.createProjectionLayer(o),i.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),_=new sn(h.textureWidth,h.textureHeight,{format:ge,type:ne,depthTexture:new rs(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:m.stencil,colorSpace:e.outputColorSpace,samples:m.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.ignoreDepthValues})}else{const n={antialias:m.antialias,alpha:!0,depth:m.depth,stencil:m.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,t,n),i.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),_=new sn(d.framebufferWidth,d.framebufferHeight,{format:ge,type:ne,colorSpace:e.outputColorSpace,stencilBuffer:m.stencil,resolveDepthBuffer:!1===d.ignoreDepthValues,resolveStencilBuffer:!1===d.ignoreDepthValues})}_.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),I.setContext(i),I.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode},this.getDepthTexture=function(){return f.getDepthTexture()};const P=new un,D=new un;function U(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(null===i)return;let t=e.near,n=e.far;null!==f.texture&&(f.depthNear>0&&(t=f.depthNear),f.depthFar>0&&(n=f.depthFar)),E.near=T.near=S.near=t,E.far=T.far=S.far=n,w===E.near&&A===E.far||(i.updateRenderState({depthNear:E.near,depthFar:E.far}),w=E.near,A=E.far),S.layers.mask=2|e.layers.mask,T.layers.mask=4|e.layers.mask,E.layers.mask=S.layers.mask|T.layers.mask;const r=e.parent,s=E.cameras;U(E,r);for(let e=0;e0&&(e.alphaTest.value=i.alphaTest);const r=t.get(i),s=r.envMap,a=r.envMapRotation;s&&(e.envMap.value=s,Kl.copy(a),Kl.x*=-1,Kl.y*=-1,Kl.z*=-1,s.isCubeTexture&&!1===s.isRenderTargetTexture&&(Kl.y*=-1,Kl.z*=-1),e.envMapRotation.value.setFromMatrix4(Zl.makeRotationFromEuler(Kl)),e.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,e.reflectivity.value=i.reflectivity,e.ior.value=i.ior,e.refractionRatio.value=i.refractionRatio),i.lightMap&&(e.lightMap.value=i.lightMap,e.lightMapIntensity.value=i.lightMapIntensity,n(i.lightMap,e.lightMapTransform)),i.aoMap&&(e.aoMap.value=i.aoMap,e.aoMapIntensity.value=i.aoMapIntensity,n(i.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,vr(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,r,s,a,o){r.isMeshBasicMaterial||r.isMeshLambertMaterial?i(e,r):r.isMeshToonMaterial?(i(e,r),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,r)):r.isMeshPhongMaterial?(i(e,r),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,r)):r.isMeshStandardMaterial?(i(e,r),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform));e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform));t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,r),r.isMeshPhysicalMaterial&&function(e,t,i){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform)));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),1===t.side&&e.clearcoatNormalScale.value.negate()));t.dispersion>0&&(e.dispersion.value=t.dispersion);t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform)));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=i.texture,e.transmissionSamplerSize.value.set(i.width,i.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,r,o)):r.isMeshMatcapMaterial?(i(e,r),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,r)):r.isMeshDepthMaterial?i(e,r):r.isMeshDistanceMaterial?(i(e,r),function(e,n){const i=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(i.matrixWorld),e.nearDistance.value=i.shadow.camera.near,e.farDistance.value=i.shadow.camera.far}(e,r)):r.isMeshNormalMaterial?i(e,r):r.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}(e,r),r.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,r)):r.isPointsMaterial?function(e,t,i,r){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*i,e.scale.value=.5*r,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r,s,a):r.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,r):r.isShadowMaterial?(e.color.value.copy(r.color),e.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function Jl(e,t,n,i){let r={},s={},a=[];const o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(e,t,n,i){const r=e.value,s=t+"_"+n;if(void 0===i[s])return i[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const e=i[s];if("number"==typeof r||"boolean"==typeof r){if(e!==r)return i[s]=r,!0}else if(!1===e.equals(r))return e.copy(r),!0}return!1}function u(e){const t={boundary:0,storage:0};return"number"==typeof e||"boolean"==typeof e?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",e),t}function c(t){const n=t.target;n.removeEventListener("dispose",c);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),e.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(e,t){const n=t.program;i.uniformBlockBinding(e,n)},update:function(n,h){let d=r[n.id];void 0===d&&(!function(e){const t=e.uniforms;let n=0;const i=16;for(let e=0,r=t.length;e0&&(n+=i-r);e.__size=n,e.__cache={}}(n),d=function(t){const n=function(){for(let e=0;e0){const e=du[0].object;eu.setFromNormalAndCoplanarPoint(t.getWorldDirection(eu.normal),au.setFromMatrixPosition(e.matrixWorld)),hu!==e&&null!==hu&&(this.dispatchEvent({type:"hoveroff",object:hu}),n.style.cursor="auto",hu=null),hu!==e&&(this.dispatchEvent({type:"hoveron",object:e}),n.style.cursor="pointer",hu=e)}else null!==hu&&(this.dispatchEvent({type:"hoveroff",object:hu}),n.style.cursor="auto",hu=null);ru.copy(tu)}}function vu(e){const t=this.object,n=this.domElement,i=this.raycaster;!1!==this.enabled&&(this._updatePointer(e),this._updateState(e),du.length=0,i.setFromCamera(tu,t),i.intersectObjects(this.objects,this.recursive,du),du.length>0&&(cu=!0===this.transformGroup?bu(du[0].object):du[0].object,eu.setFromNormalAndCoplanarPoint(t.getWorldDirection(eu.normal),au.setFromMatrixPosition(cu.matrixWorld)),i.ray.intersectPlane(eu,su)&&(this.state===fu?(ou.copy(cu.parent.matrixWorld).invert(),nu.copy(su).sub(au.setFromMatrixPosition(cu.matrixWorld))):this.state===mu&&(lu.set(0,1,0).applyQuaternion(t.quaternion).normalize(),uu.set(1,0,0).applyQuaternion(t.quaternion).normalize())),n.style.cursor="move",this.dispatchEvent({type:"dragstart",object:cu})),ru.copy(tu))}function yu(){!1!==this.enabled&&(cu&&(this.dispatchEvent({type:"dragend",object:cu}),cu=null),this.domElement.style.cursor=hu?"pointer":"auto",this.state=pu)}function xu(e){!1!==this.enabled&&e.preventDefault()}function bu(e,t=null){return e.isGroup&&(t=e),null===e.parent?t:bu(e.parent,t)}function Su(e,t,n){var i,r=1;function s(){var s,a,o=i.length,l=0,u=0,c=0;for(s=0;s=(r=(h+d)/2))?h=r:d=r,i=u,!(u=u[o=+a]))return i[o]=c,e;if(t===(s=+e._x.call(null,u.data)))return c.next=u,i?i[o]=c:e._root=c,e;do{i=i?i[o]=new Array(2):e._root=new Array(2),(a=t>=(r=(h+d)/2))?h=r:d=r}while((o=+a)==(l=+(s>=r)));return i[l]=u,i[o]=c,e}function Mu(e,t,n){this.node=e,this.x0=t,this.x1=n}function Eu(e){return e[0]}function wu(e,t){var n=new Au(null==t?Eu:t,NaN,NaN);return null==e?n:n.addAll(e)}function Au(e,t,n){this._x=e,this._x0=t,this._x1=n,this._root=void 0}function Ru(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var Cu=wu.prototype=Au.prototype;function Nu(e,t,n,i){if(isNaN(t)||isNaN(n))return e;var r,s,a,o,l,u,c,h,d,p=e._root,f={data:i},m=e._x0,g=e._y0,_=e._x1,v=e._y1;if(!p)return e._root=f,e;for(;p.length;)if((u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a,r=p,!(p=p[h=c<<1|u]))return r[h]=f,e;if(o=+e._x.call(null,p.data),l=+e._y.call(null,p.data),t===o&&n===l)return f.next=p,r?r[h]=f:e._root=f,e;do{r=r?r[h]=new Array(4):e._root=new Array(4),(u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a}while((h=c<<1|u)==(d=(l>=a)<<1|o>=s));return r[d]=p,r[h]=f,e}function Pu(e,t,n,i,r){this.node=e,this.x0=t,this.y0=n,this.x1=i,this.y1=r}function Du(e){return e[0]}function Uu(e){return e[1]}function Lu(e,t,n){var i=new Iu(null==t?Du:t,null==n?Uu:n,NaN,NaN,NaN,NaN);return null==e?i:i.addAll(e)}function Iu(e,t,n,i,r,s){this._x=e,this._y=t,this._x0=n,this._y0=i,this._x1=r,this._y1=s,this._root=void 0}function Ou(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}Cu.copy=function(){var e,t,n=new Au(this._x,this._x0,this._x1),i=this._root;if(!i)return n;if(!i.length)return n._root=Ru(i),n;for(e=[{source:i,target:n._root=new Array(2)}];i=e.pop();)for(var r=0;r<2;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(2)}):i.target[r]=Ru(t));return n},Cu.add=function(e){const t=+this._x.call(null,e);return Tu(this.cover(t),t,e)},Cu.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t);let i=1/0,r=-1/0;for(let s,a=0;ar&&(r=s));if(i>r)return this;this.cover(i).cover(r);for(let i=0;ie||e>=n;)switch(r=+(el||(r=s.x1)=h))&&(s=u[u.length-1],u[u.length-1]=u[u.length-1-a],u[u.length-1-a]=s)}else{var d=Math.abs(e-+this._x.call(null,c.data));d=(a=(h+d)/2))?h=a:d=a,t=c,!(c=c[l=+o]))return this;if(!c.length)break;t[l+1&1]&&(n=t,u=l)}for(;c.data!==e;)if(i=c,!(c=c.next))return this;return(r=c.next)&&delete c.next,i?(r?i.next=r:delete i.next,this):t?(r?t[l]=r:delete t[l],(c=t[0]||t[1])&&c===(t[1]||t[0])&&!c.length&&(n?n[u]=c:this._root=c),this):(this._root=r,this)},Cu.removeAll=function(e){for(var t=0,n=e.length;t=(a=(y+S)/2))?y=a:S=a,(p=n>=(o=(x+T)/2))?x=o:T=o,(f=i>=(l=(b+M)/2))?b=l:M=l,s=_,!(_=_[m=f<<2|p<<1|d]))return s[m]=v,e;if(u=+e._x.call(null,_.data),c=+e._y.call(null,_.data),h=+e._z.call(null,_.data),t===u&&n===c&&i===h)return v.next=_,s?s[m]=v:e._root=v,e;do{s=s?s[m]=new Array(8):e._root=new Array(8),(d=t>=(a=(y+S)/2))?y=a:S=a,(p=n>=(o=(x+T)/2))?x=o:T=o,(f=i>=(l=(b+M)/2))?b=l:M=l}while((m=f<<2|p<<1|d)==(g=(h>=l)<<2|(c>=o)<<1|u>=a));return s[g]=_,s[m]=v,e}function ku(e,t,n,i,r,s,a){this.node=e,this.x0=t,this.y0=n,this.z0=i,this.x1=r,this.y1=s,this.z1=a}Fu.copy=function(){var e,t,n=new Iu(this._x,this._y,this._x0,this._y0,this._x1,this._y1),i=this._root;if(!i)return n;if(!i.length)return n._root=Ou(i),n;for(e=[{source:i,target:n._root=new Array(4)}];i=e.pop();)for(var r=0;r<4;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(4)}):i.target[r]=Ou(t));return n},Fu.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e);return Nu(this.cover(t,n),t,n,e)},Fu.addAll=function(e){var t,n,i,r,s=e.length,a=new Array(s),o=new Array(s),l=1/0,u=1/0,c=-1/0,h=-1/0;for(n=0;nc&&(c=i),rh&&(h=r));if(l>c||u>h)return this;for(this.cover(l,u).cover(c,h),n=0;ne||e>=r||i>t||t>=s;)switch(o=(td||(s=l.y0)>p||(a=l.x1)=_)<<1|e>=g)&&(l=f[f.length-1],f[f.length-1]=f[f.length-1-u],f[f.length-1-u]=l)}else{var v=e-+this._x.call(null,m.data),y=t-+this._y.call(null,m.data),x=v*v+y*y;if(x=(o=(f+g)/2))?f=o:g=o,(c=a>=(l=(m+_)/2))?m=l:_=l,t=p,!(p=p[h=c<<1|u]))return this;if(!p.length)break;(t[h+1&3]||t[h+2&3]||t[h+3&3])&&(n=t,d=h)}for(;p.data!==e;)if(i=p,!(p=p.next))return this;return(r=p.next)&&delete p.next,i?(r?i.next=r:delete i.next,this):t?(r?t[h]=r:delete t[h],(p=t[0]||t[1]||t[2]||t[3])&&p===(t[3]||t[2]||t[1]||t[0])&&!p.length&&(n?n[d]=p:this._root=p),this):(this._root=r,this)},Fu.removeAll=function(e){for(var t=0,n=e.length;tMath.sqrt((e-i)**2+(t-r)**2+(n-s)**2);function Gu(e){return e[0]}function Vu(e){return e[1]}function Hu(e){return e[2]}function ju(e,t,n,i){var r=new Wu(null==t?Gu:t,null==n?Vu:n,null==i?Hu:i,NaN,NaN,NaN,NaN,NaN,NaN);return null==e?r:r.addAll(e)}function Wu(e,t,n,i,r,s,a,o,l){this._x=e,this._y=t,this._z=n,this._x0=i,this._y0=r,this._z0=s,this._x1=a,this._y1=o,this._z1=l,this._root=void 0}function Xu(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var qu=ju.prototype=Wu.prototype;function $u(e){return function(){return e}}function Yu(e){return 1e-6*(e()-.5)}function Ku(e){return e.index}function Zu(e,t){var n=e.get(t);if(!n)throw new Error("node not found: "+t);return n}function Qu(e){var t,n,i,r,s,a,o,l=Ku,u=function(e){return 1/Math.min(s[e.source.index],s[e.target.index])},c=$u(30),h=1;function d(i){for(var s=0,l=e.length;s1&&(_=d.y+d.vy-c.y-c.vy||Yu(o)),r>2&&(v=d.z+d.vz-c.z-c.vz||Yu(o)),g*=p=((p=Math.sqrt(g*g+_*_+v*v))-n[m])/p*i*t[m],_*=p,v*=p,d.vx-=g*(f=a[m]),r>1&&(d.vy-=_*f),r>2&&(d.vz-=v*f),c.vx+=g*(f=1-f),r>1&&(c.vy+=_*f),r>2&&(c.vz+=v*f)}function p(){if(i){var r,o,u=i.length,c=e.length,h=new Map(i.map(((e,t)=>[l(e,t,i),e])));for(r=0,s=new Array(u);r"function"==typeof e))||Math.random,r=t.find((e=>[1,2,3].includes(e)))||2,p()},d.links=function(t){return arguments.length?(e=t,p(),d):e},d.id=function(e){return arguments.length?(l=e,d):l},d.iterations=function(e){return arguments.length?(h=+e,d):h},d.strength=function(e){return arguments.length?(u="function"==typeof e?e:$u(+e),f(),d):u},d.distance=function(e){return arguments.length?(c="function"==typeof e?e:$u(+e),m(),d):c},d}qu.copy=function(){var e,t,n=new Wu(this._x,this._y,this._z,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1),i=this._root;if(!i)return n;if(!i.length)return n._root=Xu(i),n;for(e=[{source:i,target:n._root=new Array(8)}];i=e.pop();)for(var r=0;r<8;++r)(t=i.source[r])&&(t.length?e.push({source:t,target:i.target[r]=new Array(8)}):i.target[r]=Xu(t));return n},qu.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e),i=+this._z.call(null,e);return Bu(this.cover(t,n,i),t,n,i,e)},qu.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t),i=new Float64Array(t),r=new Float64Array(t);let s=1/0,a=1/0,o=1/0,l=-1/0,u=-1/0,c=-1/0;for(let h,d,p,f,m=0;ml&&(l=d),pu&&(u=p),fc&&(c=f));if(s>l||a>u||o>c)return this;this.cover(s,a,o).cover(l,u,c);for(let s=0;se||e>=a||r>t||t>=o||s>n||n>=l;)switch(c=(ng||(a=h.y0)>_||(o=h.z0)>v||(l=h.x1)=T)<<2|(t>=S)<<1|e>=b)&&(h=y[y.length-1],y[y.length-1]=y[y.length-1-d],y[y.length-1-d]=h)}else{var M=e-+this._x.call(null,x.data),E=t-+this._y.call(null,x.data),w=n-+this._z.call(null,x.data),A=M*M+E*E+w*w;if(A{if(!h.length)do{const s=h.data;zu(e,t,n,this._x(s),this._y(s),this._z(s))<=i&&r.push(s)}while(h=h.next);return d>l||p>u||f>c||m=(l=(_+x)/2))?_=l:x=l,(d=a>=(u=(v+b)/2))?v=u:b=u,(p=o>=(c=(y+S)/2))?y=c:S=c,t=g,!(g=g[f=p<<2|d<<1|h]))return this;if(!g.length)break;(t[f+1&7]||t[f+2&7]||t[f+3&7]||t[f+4&7]||t[f+5&7]||t[f+6&7]||t[f+7&7])&&(n=t,m=f)}for(;g.data!==e;)if(i=g,!(g=g.next))return this;return(r=g.next)&&delete g.next,i?(r?i.next=r:delete i.next,this):t?(r?t[f]=r:delete t[f],(g=t[0]||t[1]||t[2]||t[3]||t[4]||t[5]||t[6]||t[7])&&g===(t[7]||t[6]||t[5]||t[4]||t[3]||t[2]||t[1]||t[0])&&!g.length&&(n?n[m]=g:this._root=g),this):(this._root=r,this)},qu.removeAll=function(e){for(var t=0,n=e.length;t{}};function ec(){for(var e,t=0,n=arguments.length,i={};t=0&&(t=e.slice(n+1),e=e.slice(0,n)),e&&!i.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:t}}))),a=-1,o=s.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++a0)for(var n,i,r=new Array(n),s=0;s=0&&t._call.call(void 0,e),t=t._next;--ac}()}finally{ac=0,function(){var e,t,n=rc,i=1/0;for(;n;)n._call?(i>n._time&&(i=n._time),e=n,n=n._next):(t=n._next,n._next=null,n=e?e._next=t:rc=t);sc=e,xc(i)}(),cc=0}}function yc(){var e=dc.now(),t=e-uc;t>1e3&&(hc-=t,uc=e)}function xc(e){ac||(oc&&(oc=clearTimeout(oc)),e-cc>24?(e<1/0&&(oc=setTimeout(vc,e-dc.now()-hc)),lc&&(lc=clearInterval(lc))):(lc||(uc=dc.now(),lc=setInterval(yc,1e3)),ac=1,pc(vc)))}gc.prototype=_c.prototype={constructor:gc,restart:function(e,t,n){if("function"!=typeof e)throw new TypeError("callback is not a function");n=(null==n?fc():+n)+(null==t?0:+t),this._next||sc===this||(sc?sc._next=this:rc=this,sc=this),this._call=e,this._time=n,xc()},stop:function(){this._call&&(this._call=null,this._time=1/0,xc())}};const bc=4294967296;function Sc(e){return e.x}function Tc(e){return e.y}function Mc(e){return e.z}var Ec,wc,Ac,Rc,Cc=Math.PI*(3-Math.sqrt(5)),Nc=20*Math.PI/(9+Math.sqrt(221));function Pc(e,t){t=t||2;var n,i=Math.min(3,Math.max(1,Math.round(t))),r=1,s=.001,a=1-Math.pow(s,1/300),o=0,l=.6,u=new Map,c=_c(p),h=ec("tick","end"),d=function(){let e=1;return()=>(e=(1664525*e+1013904223)%bc)/bc}();function p(){f(),h.call("tick",n),r1&&(null==c.fy?c.y+=c.vy*=l:(c.y=c.fy,c.vy=0)),i>2&&(null==c.fz?c.z+=c.vz*=l:(c.z=c.fz,c.vz=0));return n}function m(){for(var t,n=0,r=e.length;n1&&isNaN(t.y)||i>2&&isNaN(t.z)){var s=10*(i>2?Math.cbrt(.5+n):i>1?Math.sqrt(.5+n):n),a=n*Cc,o=n*Nc;1===i?t.x=s:2===i?(t.x=s*Math.cos(a),t.y=s*Math.sin(a)):(t.x=s*Math.sin(a)*Math.cos(o),t.y=s*Math.cos(a),t.z=s*Math.sin(a)*Math.sin(o))}(isNaN(t.vx)||i>1&&isNaN(t.vy)||i>2&&isNaN(t.vz))&&(t.vx=0,i>1&&(t.vy=0),i>2&&(t.vz=0))}}function g(t){return t.initialize&&t.initialize(e,d,i),t}return null==e&&(e=[]),m(),n={tick:f,restart:function(){return c.restart(p),n},stop:function(){return c.stop(),n},numDimensions:function(e){return arguments.length?(i=Math.min(3,Math.max(1,Math.round(e))),u.forEach(g),n):i},nodes:function(t){return arguments.length?(e=t,m(),u.forEach(g),n):e},alpha:function(e){return arguments.length?(r=+e,n):r},alphaMin:function(e){return arguments.length?(s=+e,n):s},alphaDecay:function(e){return arguments.length?(a=+e,n):+a},alphaTarget:function(e){return arguments.length?(o=+e,n):o},velocityDecay:function(e){return arguments.length?(l=1-e,n):1-l},randomSource:function(e){return arguments.length?(d=e,u.forEach(g),n):d},force:function(e,t){return arguments.length>1?(null==t?u.delete(e):u.set(e,g(t)),n):u.get(e)},find:function(){var t,n,r,s,a,o,l=Array.prototype.slice.call(arguments),u=l.shift()||0,c=(i>1?l.shift():null)||0,h=(i>2?l.shift():null)||0,d=l.shift()||1/0,p=0,f=e.length;for(d*=d,p=0;p1?(h.on(e,t),n):h.on(e)}}}function Dc(){var e,t,n,i,r,s,a=$u(-30),o=1,l=1/0,u=.81;function c(i){var s,a=e.length,o=(1===t?wu(e,Sc):2===t?Lu(e,Sc,Tc):3===t?ju(e,Sc,Tc,Mc):null).visitAfter(d);for(r=i,s=0;s1&&(e.y=a/c),t>2&&(e.z=o/c)}else{(n=e).x=n.data.x,t>1&&(n.y=n.data.y),t>2&&(n.z=n.data.z);do{u+=s[n.data.index]}while(n=n.next)}e.value=u}function p(e,a,c,h,d){if(!e.value)return!0;var p=[c,h,d][t-1],f=e.x-n.x,m=t>1?e.y-n.y:0,g=t>2?e.z-n.z:0,_=p-a,v=f*f+m*m+g*g;if(_*_/u1&&0===m&&(v+=(m=Yu(i))*m),t>2&&0===g&&(v+=(g=Yu(i))*g),v1&&(n.vy+=m*e.value*r/v),t>2&&(n.vz+=g*e.value*r/v)),!0;if(!(e.length||v>=l)){(e.data!==n||e.next)&&(0===f&&(v+=(f=Yu(i))*f),t>1&&0===m&&(v+=(m=Yu(i))*m),t>2&&0===g&&(v+=(g=Yu(i))*g),v1&&(n.vy+=m*_),t>2&&(n.vz+=g*_))}while(e=e.next)}}return c.initialize=function(n,...r){e=n,i=r.find((e=>"function"==typeof e))||Math.random,t=r.find((e=>[1,2,3].includes(e)))||2,h()},c.strength=function(e){return arguments.length?(a="function"==typeof e?e:$u(+e),h(),c):a},c.distanceMin=function(e){return arguments.length?(o=e*e,c):Math.sqrt(o)},c.distanceMax=function(e){return arguments.length?(l=e*e,c):Math.sqrt(l)},c.theta=function(e){return arguments.length?(u=e*e,c):Math.sqrt(u)},c}function Uc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Lc(){if(wc)return Ec;return wc=1,Ec=function(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");for(var t=["on","fire","off"],n=0;n1&&(i=Array.prototype.splice.call(arguments,1));for(var s=0;s0&&(g.fire("changed",h),h.length=0)}function C(e){if("function"!=typeof e)throw new Error("Function is expected to iterate over graph nodes. You passed "+e);for(var t=a.values(),n=t.next();!n.done;){if(e(n.value))return!0;n=t.next()}}};var e=Lc();function t(e,t){this.id=e,this.links=null,this.data=t}function n(e,t){e.links?e.links.add(t):e.links=new Set([t])}function i(e,t,n,i){this.fromId=e,this.toId=t,this.data=n,this.id=i}function r(e,t){return e.toString()+"👉 "+t.toString()}return Ac}(),Gc=Uc(zc),Vc={exports:{}},Hc={exports:{}};function jc(){return Oc||(Oc=1,Ic=function(e){return 0===e?"x":1===e?"y":2===e?"z":"c"+(e+1)}),Ic}function Wc(){if(Bc)return Fc;Bc=1;const e=jc();return Fc=function(t){return function(n,i){let r=i&&i.indent||0,s=i&&void 0!==i.join?i.join:"\n",a=Array(r+1).join(" "),o=[];for(let i=0;i>>19))+(e<<5)&4294967295)^e<<9))+(e<<3)&4294967295)^e>>>16),this.seed=e,(268435455&e)/268435456}return ah=1,ch.exports=e,ch.exports.random=e,ch.exports.randomIterator=function(t,n){var i=n||e();if("function"!=typeof i.next)throw new Error("customRandom does not match expected API: next() function is missing");return{forEach:function(e){var n,r,s;for(n=t.length-1;n>0;--n)r=i.next(n+1),s=t[r],t[r]=t[n],t[n]=s,e(s);t.length&&e(t[0])},shuffle:function(){var e,n,r;for(e=t.length-1;e>0;--e)n=i.next(e+1),r=t[n],t[n]=t[e],t[e]=r;return t}}},t.prototype.next=function(e){return Math.floor(this.nextDouble()*e)},t.prototype.nextDouble=i,t.prototype.uniform=i,t.prototype.gaussian=function(){var e,t,n;do{e=(t=2*this.nextDouble()-1)*t+(n=2*this.nextDouble()-1)*n}while(e>=1||0===e);return t*Math.sqrt(-2*Math.log(e)/e)},t.prototype.levy=function(){var e=1.5,t=Math.pow(n(2.5)*Math.sin(Math.PI*e/2)/(n(1.25)*e*Math.pow(2,.25)),1/e);return this.gaussian()*t/Math.pow(Math.abs(this.gaussian()),1/e)},ch.exports}().random(42),b=[],S=[],T=m(l,x),M=g(b,l,x),E=v(l,x),w=_(l),A=[],R=new Map,C=0;D("nbody",(function(){if(0===b.length)return;T.insertBodies(b);var e=b.length;for(;e--;){var t=b[e];t.isPinned||(t.reset(),T.updateBodyForce(t),w.update(t))}})),D("spring",(function(){var e=S.length;for(;e--;)E.update(S[e])}));var N={bodies:b,quadTree:T,springs:S,settings:l,addForce:D,removeForce:function(e){var t=A.indexOf(R.get(e));if(t<0)return;A.splice(t,1),R.delete(e)},getForces:function(){return R},step:function(){for(var e=0;enew f(e))(e);return b.push(t),t},removeBody:function(e){if(e){var t=b.indexOf(e);if(!(t<0))return b.splice(t,1),0===b.length&&M.reset(),!0}},addSpring:function(e,t,n,i){if(!e||!t)throw new Error("Cannot add null spring to force simulator");"number"!=typeof n&&(n=-1);var r=new u(e,t,n,i>=0?i:-1);return S.push(r),r},getTotalMovement:function(){return 0},removeSpring:function(e){if(e){var t=S.indexOf(e);return t>-1?(S.splice(t,1),!0):void 0}},getBestNewBodyPosition:function(e){return M.getBestNewPosition(e)},getBBox:P,getBoundingBox:P,invalidateBBox:function(){console.warn("invalidateBBox() is deprecated, bounds always recomputed on `getBBox()` call")},gravity:function(e){return void 0!==e?(l.gravity=e,T.options({gravity:e}),this):l.gravity},theta:function(e){return void 0!==e?(l.theta=e,T.options({theta:e}),this):l.theta},random:x};return function(e,t){for(var n in e)o(e,t,n)}(l,N),h(N),N;function P(){return M.update(),M.box}function D(e,t){if(R.has(e))throw new Error("Force "+e+" is already added");R.set(e,t),A.push(t)}};var e=function(){if(kc)return Hc.exports;kc=1;const e=Wc();function t(e,t){return`\n${i(e,t)}\n${n(e)}\nreturn {Body: Body, Vector: Vector};\n`}function n(t){let n=e(t),i=n("{var}",{join:", "});return`\nfunction Body(${i}) {\n this.isPinned = false;\n this.pos = new Vector(${i});\n this.force = new Vector();\n this.velocity = new Vector();\n this.mass = 1;\n\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.reset = function() {\n this.force.reset();\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.setPosition = function (${i}) {\n ${n("this.pos.{var} = {var} || 0;",{indent:2})}\n};`}function i(t,n){let i=e(t),r="";return n&&(r=`${i("\n\t var v{var};\n\tObject.defineProperty(this, '{var}', {\n\t set: function(v) { \n\t if (!Number.isFinite(v)) throw new Error('Cannot set non-numbers to {var}');\n\t v{var} = v; \n\t },\n\t get: function() { return v{var}; }\n\t});")}`),`function Vector(${i("{var}",{join:", "})}) {\n ${r}\n if (typeof arguments[0] === 'object') {\n // could be another vector\n let v = arguments[0];\n ${i('if (!Number.isFinite(v.{var})) throw new Error("Expected value is not a finite number at Vector constructor ({var})");',{indent:4})}\n ${i("this.{var} = v.{var};",{indent:4})}\n } else {\n ${i('this.{var} = typeof {var} === "number" ? {var} : 0;',{indent:4})}\n }\n }\n \n Vector.prototype.reset = function () {\n ${i("this.{var} = ",{join:""})}0;\n };`}return Hc.exports=function(e,n){let i=t(e,n),{Body:r}=new Function(i)();return r},Hc.exports.generateCreateBodyFunctionBody=t,Hc.exports.getVectorCode=i,Hc.exports.getBodyCode=n,Hc.exports}(),t=function(){if(Xc)return qc.exports;Xc=1;const e=Wc(),t=jc();function n(n){let l=e(n),u=Math.pow(2,n),c=`\n${o()}\n${a(n)}\n${i(n)}\n${s(n)}\n${r(n)}\n\nfunction createQuadTree(options, random) {\n options = options || {};\n options.gravity = typeof options.gravity === 'number' ? options.gravity : -1;\n options.theta = typeof options.theta === 'number' ? options.theta : 0.8;\n\n var gravity = options.gravity;\n var updateQueue = [];\n var insertStack = new InsertStack();\n var theta = options.theta;\n\n var nodesCache = [];\n var currentInCache = 0;\n var root = newNode();\n\n return {\n insertBodies: insertBodies,\n\n /**\n * Gets root node if it is present\n */\n getRoot: function() {\n return root;\n },\n\n updateBodyForce: update,\n\n options: function(newOptions) {\n if (newOptions) {\n if (typeof newOptions.gravity === 'number') {\n gravity = newOptions.gravity;\n }\n if (typeof newOptions.theta === 'number') {\n theta = newOptions.theta;\n }\n\n return this;\n }\n\n return {\n gravity: gravity,\n theta: theta\n };\n }\n };\n\n function newNode() {\n // To avoid pressure on GC we reuse nodes.\n var node = nodesCache[currentInCache];\n if (node) {\n${function(e){let t=[];for(let n=0;n {var}max) {var}max = pos.{var};",{indent:6})}\n }\n\n // Makes the bounds square.\n var maxSideLength = -Infinity;\n ${l("if ({var}max - {var}min > maxSideLength) maxSideLength = {var}max - {var}min ;",{indent:4})}\n\n currentInCache = 0;\n root = newNode();\n ${l("root.min_{var} = {var}min;",{indent:4})}\n ${l("root.max_{var} = {var}min + maxSideLength;",{indent:4})}\n\n i = bodies.length - 1;\n if (i >= 0) {\n root.body = bodies[i];\n }\n while (i--) {\n insert(bodies[i], root);\n }\n }\n\n function insert(newBody) {\n insertStack.reset();\n insertStack.push(root, newBody);\n\n while (!insertStack.isEmpty()) {\n var stackItem = insertStack.pop();\n var node = stackItem.node;\n var body = stackItem.body;\n\n if (!node.body) {\n // This is internal node. Update the total mass of the node and center-of-mass.\n ${l("var {var} = body.pos.{var};",{indent:8})}\n node.mass += body.mass;\n ${l("node.mass_{var} += body.mass * {var};",{indent:8})}\n\n // Recursively insert the body in the appropriate quadrant.\n // But first find the appropriate quadrant.\n var quadIdx = 0; // Assume we are in the 0's quad.\n ${l("var min_{var} = node.min_{var};",{indent:8})}\n ${l("var max_{var} = (min_{var} + node.max_{var}) / 2;",{indent:8})}\n\n${function(){let e=[],i=Array(8+1).join(" ");for(let r=0;r max_${t(r)}) {`),e.push(i+` quadIdx = quadIdx + ${Math.pow(2,r)};`),e.push(i+` min_${t(r)} = max_${t(r)};`),e.push(i+` max_${t(r)} = node.max_${t(r)};`),e.push(i+"}");return e.join("\n")}()}\n\n var child = getChild(node, quadIdx);\n\n if (!child) {\n // The node is internal but this quadrant is not taken. Add\n // subnode to it.\n child = newNode();\n ${l("child.min_{var} = min_{var};",{indent:10})}\n ${l("child.max_{var} = max_{var};",{indent:10})}\n child.body = body;\n\n setChild(node, quadIdx, child);\n } else {\n // continue searching in this quadrant.\n insertStack.push(child, body);\n }\n } else {\n // We are trying to add to the leaf node.\n // We have to convert current leaf into internal node\n // and continue adding two nodes.\n var oldBody = node.body;\n node.body = null; // internal nodes do not cary bodies\n\n if (isSamePosition(oldBody.pos, body.pos)) {\n // Prevent infinite subdivision by bumping one node\n // anywhere in this quadrant\n var retriesCount = 3;\n do {\n var offset = random.nextDouble();\n ${l("var d{var} = (node.max_{var} - node.min_{var}) * offset;",{indent:12})}\n\n ${l("oldBody.pos.{var} = node.min_{var} + d{var};",{indent:12})}\n retriesCount -= 1;\n // Make sure we don't bump it out of the box. If we do, next iteration should fix it\n } while (retriesCount > 0 && isSamePosition(oldBody.pos, body.pos));\n\n if (retriesCount === 0 && isSamePosition(oldBody.pos, body.pos)) {\n // This is very bad, we ran out of precision.\n // if we do not return from the method we'll get into\n // infinite loop here. So we sacrifice correctness of layout, and keep the app running\n // Next layout iteration should get larger bounding box in the first step and fix this\n return;\n }\n }\n // Next iteration should subdivide node further.\n insertStack.push(node, oldBody);\n insertStack.push(node, body);\n }\n }\n }\n}\nreturn createQuadTree;\n\n`;return c}function i(t){let n=e(t);return`\n function isSamePosition(point1, point2) {\n ${n("var d{var} = Math.abs(point1.{var} - point2.{var});",{indent:2})}\n \n return ${n("d{var} < 1e-8",{join:" && "})};\n } \n`}function r(e){var t=Math.pow(2,e);return`\nfunction setChild(node, idx, child) {\n ${function(){let e=[];for(let n=0;n 0) {\n return this.stack[--this.popIdx];\n }\n },\n reset: function () {\n this.popIdx = 0;\n }\n};\n\nfunction InsertStackElement(node, body) {\n this.node = node; // QuadTree node\n this.body = body; // physical body which needs to be inserted to node\n}\n"}return qc.exports=function(e){let t=n(e);return new Function(t)()},qc.exports.generateQuadTreeFunctionBody=n,qc.exports.getInsertStackCode=o,qc.exports.getQuadNodeCode=a,qc.exports.isSamePosition=i,qc.exports.getChildBodyCode=s,qc.exports.setChildBodyCode=r,qc.exports}(),n=function(){if($c)return Yc.exports;$c=1,Yc.exports=function(e){let n=t(e);return new Function("bodies","settings","random",n)},Yc.exports.generateFunctionBody=t;const e=Wc();function t(t){let n=e(t);return`\n var boundingBox = {\n ${n("min_{var}: 0, max_{var}: 0,",{indent:4})}\n };\n\n return {\n box: boundingBox,\n\n update: updateBoundingBox,\n\n reset: resetBoundingBox,\n\n getBestNewPosition: function (neighbors) {\n var ${n("base_{var} = 0",{join:", "})};\n\n if (neighbors.length) {\n for (var i = 0; i < neighbors.length; ++i) {\n let neighborPos = neighbors[i].pos;\n ${n("base_{var} += neighborPos.{var};",{indent:10})}\n }\n\n ${n("base_{var} /= neighbors.length;",{indent:8})}\n } else {\n ${n("base_{var} = (boundingBox.min_{var} + boundingBox.max_{var}) / 2;",{indent:8})}\n }\n\n var springLength = settings.springLength;\n return {\n ${n("{var}: base_{var} + (random.nextDouble() - 0.5) * springLength,",{indent:8})}\n };\n }\n };\n\n function updateBoundingBox() {\n var i = bodies.length;\n if (i === 0) return; // No bodies - no borders.\n\n ${n("var max_{var} = -Infinity;",{indent:4})}\n ${n("var min_{var} = Infinity;",{indent:4})}\n\n while(i--) {\n // this is O(n), it could be done faster with quadtree, if we check the root node bounds\n var bodyPos = bodies[i].pos;\n ${n("if (bodyPos.{var} < min_{var}) min_{var} = bodyPos.{var};",{indent:6})}\n ${n("if (bodyPos.{var} > max_{var}) max_{var} = bodyPos.{var};",{indent:6})}\n }\n\n ${n("boundingBox.min_{var} = min_{var};",{indent:4})}\n ${n("boundingBox.max_{var} = max_{var};",{indent:4})}\n }\n\n function resetBoundingBox() {\n ${n("boundingBox.min_{var} = boundingBox.max_{var} = 0;",{indent:4})}\n }\n`}return Yc.exports}(),i=function(){if(Kc)return Zc.exports;Kc=1;const e=Wc();function t(t){return`\n if (!Number.isFinite(options.dragCoefficient)) throw new Error('dragCoefficient is not a finite number');\n\n return {\n update: function(body) {\n ${e(t)("body.force.{var} -= options.dragCoefficient * body.velocity.{var};",{indent:6})}\n }\n };\n`}return Zc.exports=function(e){let n=t(e);return new Function("options",n)},Zc.exports.generateCreateDragForceFunctionBody=t,Zc.exports}(),r=function(){if(Qc)return Jc.exports;Qc=1;const e=Wc();function t(t){let n=e(t);return`\n if (!Number.isFinite(options.springCoefficient)) throw new Error('Spring coefficient is not a number');\n if (!Number.isFinite(options.springLength)) throw new Error('Spring length is not a number');\n\n return {\n /**\n * Updates forces acting on a spring\n */\n update: function (spring) {\n var body1 = spring.from;\n var body2 = spring.to;\n var length = spring.length < 0 ? options.springLength : spring.length;\n ${n("var d{var} = body2.pos.{var} - body1.pos.{var};",{indent:6})}\n var r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n ${n("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:8})}\n r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n }\n\n var d = r - length;\n var coefficient = ((spring.coefficient > 0) ? spring.coefficient : options.springCoefficient) * d / r;\n\n ${n("body1.force.{var} += coefficient * d{var}",{indent:6})};\n body1.springCount += 1;\n body1.springLength += r;\n\n ${n("body2.force.{var} -= coefficient * d{var}",{indent:6})};\n body2.springCount += 1;\n body2.springLength += r;\n }\n };\n`}return Jc.exports=function(e){let n=t(e);return new Function("options","random",n)},Jc.exports.generateCreateSpringForceFunctionBody=t,Jc.exports}(),s=function(){if(eh)return sh.exports;eh=1;const e=Wc();function t(t){let n=e(t);return`\n var length = bodies.length;\n if (length === 0) return 0;\n\n ${n("var d{var} = 0, t{var} = 0;",{indent:2})}\n\n for (var i = 0; i < length; ++i) {\n var body = bodies[i];\n if (body.isPinned) continue;\n\n if (adaptiveTimeStepWeight && body.springCount) {\n timeStep = (adaptiveTimeStepWeight * body.springLength/body.springCount);\n }\n\n var coeff = timeStep / body.mass;\n\n ${n("body.velocity.{var} += coeff * body.force.{var};",{indent:4})}\n ${n("var v{var} = body.velocity.{var};",{indent:4})}\n var v = Math.sqrt(${n("v{var} * v{var}",{join:" + "})});\n\n if (v > 1) {\n // We normalize it so that we move within timeStep range. \n // for the case when v <= 1 - we let velocity to fade out.\n ${n("body.velocity.{var} = v{var} / v;",{indent:6})}\n }\n\n ${n("d{var} = timeStep * body.velocity.{var};",{indent:4})}\n\n ${n("body.pos.{var} += d{var};",{indent:4})}\n\n ${n("t{var} += Math.abs(d{var});",{indent:4})}\n }\n\n return (${n("t{var} * t{var}",{join:" + "})})/length;\n`}return sh.exports=function(e){let n=t(e);return new Function("bodies","timeStep","adaptiveTimeStepWeight",n)},sh.exports.generateIntegratorFunctionBody=t,sh.exports}(),a={};function o(e,t,n){if(e.hasOwnProperty(n)&&"function"!=typeof t[n]){var i=Number.isFinite(e[n]);t[n]=i?function(i){if(void 0!==i){if(!Number.isFinite(i))throw new Error("Value of "+n+" should be a valid number.");return e[n]=i,t}return e[n]}:function(i){return void 0!==i?(e[n]=i,t):e[n]}}}return oh}var dh=function(){if(uh)return Vc.exports;uh=1,Vc.exports=function(n,i){if(!n)throw new Error("Graph structure cannot be undefined");var r=(i&&i.createSimulator||hh())(i);if(Array.isArray(i))throw new Error("Physics settings is expected to be an object");var s=n.version>19?function(e){var t=n.getLinks(e);return t?1+t.size/3:1}:function(e){var t=n.getLinks(e);return t?1+t.length/3:1};i&&"function"==typeof i.nodeMass&&(s=i.nodeMass);var a=new Map,o={},l=0,u=r.settings.springTransform||t;l=0,n.forEachNode((function(e){m(e.id),l+=1})),n.forEachLink(_),n.on("changed",f);var c=!1,h={step:function(){if(0===l)return d(!0),!0;var e=r.step();h.lastMove=e,h.fire("step");var t=e/l<=.01;return d(t),t},getNodePosition:function(e){return x(e).pos},setNodePosition:function(e){var t=x(e);t.setPosition.apply(t,Array.prototype.slice.call(arguments,1))},getLinkPosition:function(e){var t=o[e];if(t)return{from:t.from.pos,to:t.to.pos}},getGraphRect:function(){return r.getBBox()},forEachBody:p,pinNode:function(e,t){x(e.id).isPinned=!!t},isNodePinned:function(e){return x(e.id).isPinned},dispose:function(){n.off("changed",f),h.fire("disposed")},getBody:function(e){return a.get(e)},getSpring:function(e,t){var i;if(void 0===t)i="object"!=typeof e?e:e.id;else{var r=n.hasLink(e,t);if(!r)return;i=r.id}return o[i]},getForceVectorLength:function(){var e=0,t=0;return p((function(n){e+=Math.abs(n.force.x),t+=Math.abs(n.force.y)})),Math.sqrt(e*e+t*t)},simulator:r,graph:n,lastMove:0};return e(h),h;function d(e){var t;c!==e&&(c=e,t=e,h.fire("stable",t))}function p(e){a.forEach(e)}function f(e){for(var t=0;t=t||n<0||h&&e-u>=s}function m(){var e=vh();if(f(e))return g(e);o=setTimeout(m,function(e){var n=t-(e-l);return h?Oh(n,s-(e-u)):n}(e))}function g(e){return o=void 0,d&&i?p(e):(i=r=void 0,a)}function _(){var e=vh(),n=f(e);if(i=arguments,r=this,l=e,n){if(void 0===o)return function(e){return u=e,o=setTimeout(m,t),c?p(e):a}(l);if(h)return clearTimeout(o),o=setTimeout(m,t),p(l)}return void 0===o&&(o=setTimeout(m,t)),a}return t=Lh(t)||0,fh(n)&&(c=!!n.leading,s=(h="maxWait"in n)?Ih(Lh(n.maxWait)||0,t):s,d="trailing"in n?!!n.trailing:d),_.cancel=function(){void 0!==o&&clearTimeout(o),u=0,i=l=r=o=void 0},_.flush=function(){return void 0===o?a:g(vh())},_}function Bh(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n=t)&&(n=t);else{let i=-1;for(let r of e)null!=(r=t(r,++i,e))&&(n=r)&&(n=r)}return n}function $h(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n>t||void 0===n&&t>=t)&&(n=t);else{let i=-1;for(let r of e)null!=(r=t(r,++i,e))&&(n>r||void 0===n&&r>=r)&&(n=r)}return n}function Yh(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=Bd(e,360),t=Bd(t,100),n=Bd(n,100),0===t)i=r=s=n;else{var o=n<.5?n*(1+t):n+t-n*t,l=2*n-o;i=a(l,o,e+1/3),r=a(l,o,e),s=a(l,o,e-1/3)}return{r:255*i,g:255*r,b:255*s}}(e.h,i,s),a=!0,o="hsl"),e.hasOwnProperty("a")&&(n=e.a));return n=Fd(n),{ok:a,format:e.format||o,r:Math.min(255,Math.max(t.r,0)),g:Math.min(255,Math.max(t.g,0)),b:Math.min(255,Math.max(t.b,0)),a:n}}(e);this._originalInput=e,this._r=n.r,this._g=n.g,this._b=n.b,this._a=n.a,this._roundA=Math.round(100*this._a)/100,this._format=t.format||n.format,this._gradientType=t.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=n.ok}function yd(e,t,n){e=Bd(e,255),t=Bd(t,255),n=Bd(n,255);var i,r,s=Math.max(e,t,n),a=Math.min(e,t,n),o=(s+a)/2;if(s==a)i=r=0;else{var l=s-a;switch(r=o>.5?l/(2-s-a):l/(s+a),s){case e:i=(t-n)/l+(t>1)+720)%360;--t;)i.h=(i.h+r)%360,s.push(vd(i));return s}function Ld(e,t){t=t||6;for(var n=vd(e).toHsv(),i=n.h,r=n.s,s=n.v,a=[],o=1/t;t--;)a.push(vd({h:i,s:r,v:s})),s=(s+o)%1;return a}vd.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var e,t,n,i=this.toRgb();return e=i.r/255,t=i.g/255,n=i.b/255,.2126*(e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))+.7152*(t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))},setAlpha:function(e){return this._a=Fd(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=xd(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=xd(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),i=Math.round(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+i+"%)":"hsva("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHsl:function(){var e=yd(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=yd(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),i=Math.round(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+i+"%)":"hsla("+t+", "+n+"%, "+i+"%, "+this._roundA+")"},toHex:function(e){return bd(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,i,r){var s=[Gd(Math.round(e).toString(16)),Gd(Math.round(t).toString(16)),Gd(Math.round(n).toString(16)),Gd(Hd(i))];if(r&&s[0].charAt(0)==s[0].charAt(1)&&s[1].charAt(0)==s[1].charAt(1)&&s[2].charAt(0)==s[2].charAt(1)&&s[3].charAt(0)==s[3].charAt(1))return s[0].charAt(0)+s[1].charAt(0)+s[2].charAt(0)+s[3].charAt(0);return s.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(100*Bd(this._r,255))+"%",g:Math.round(100*Bd(this._g,255))+"%",b:Math.round(100*Bd(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*Bd(this._r,255))+"%, "+Math.round(100*Bd(this._g,255))+"%, "+Math.round(100*Bd(this._b,255))+"%)":"rgba("+Math.round(100*Bd(this._r,255))+"%, "+Math.round(100*Bd(this._g,255))+"%, "+Math.round(100*Bd(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(Od[bd(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+Sd(this._r,this._g,this._b,this._a),n=t,i=this._gradientType?"GradientType = 1, ":"";if(e){var r=vd(e);n="#"+Sd(r._r,r._g,r._b,r._a)}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,i=this._a<1&&this._a>=0;return t||!i||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return vd(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(wd,arguments)},brighten:function(){return this._applyModification(Ad,arguments)},darken:function(){return this._applyModification(Rd,arguments)},desaturate:function(){return this._applyModification(Td,arguments)},saturate:function(){return this._applyModification(Md,arguments)},greyscale:function(){return this._applyModification(Ed,arguments)},spin:function(){return this._applyModification(Cd,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(Ud,arguments)},complement:function(){return this._applyCombination(Nd,arguments)},monochromatic:function(){return this._applyCombination(Ld,arguments)},splitcomplement:function(){return this._applyCombination(Dd,arguments)},triad:function(){return this._applyCombination(Pd,[3])},tetrad:function(){return this._applyCombination(Pd,[4])}},vd.fromRatio=function(e,t){if("object"==md(e)){var n={};for(var i in e)e.hasOwnProperty(i)&&(n[i]="a"===i?e[i]:Vd(e[i]));e=n}return vd(e,t)},vd.equals=function(e,t){return!(!e||!t)&&vd(e).toRgbString()==vd(t).toRgbString()},vd.random=function(){return vd.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},vd.mix=function(e,t,n){n=0===n?0:n||50;var i=vd(e).toRgb(),r=vd(t).toRgb(),s=n/100;return vd({r:(r.r-i.r)*s+i.r,g:(r.g-i.g)*s+i.g,b:(r.b-i.b)*s+i.b,a:(r.a-i.a)*s+i.a})}, +// =4.5;break;case"AAlarge":r=s>=3;break;case"AAAsmall":r=s>=7}return r},vd.mostReadable=function(e,t,n){var i,r,s,a,o=null,l=0;r=(n=n||{}).includeFallbackColors,s=n.level,a=n.size;for(var u=0;ul&&(l=i,o=vd(t[u]));return vd.isReadable(e,o,{level:s,size:a})||!r?o:(n.includeFallbackColors=!1,vd.mostReadable(e,["#fff","#000"],n))};var Id=vd.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Od=vd.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(Id);function Fd(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function Bd(e,t){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(e)&&(e="100%");var n=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(e);return e=Math.min(t,Math.max(0,parseFloat(e))),n&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function kd(e){return Math.min(1,Math.max(0,e))}function zd(e){return parseInt(e,16)}function Gd(e){return 1==e.length?"0"+e:""+e}function Vd(e){return e<=1&&(e=100*e+"%"),e}function Hd(e){return Math.round(255*parseFloat(e)).toString(16)}function jd(e){return zd(e)/255}var Wd,Xd,qd,$d=(Xd="[\\s|\\(]+("+(Wd="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+Wd+")[,|\\s]+("+Wd+")\\s*\\)?",qd="[\\s|\\(]+("+Wd+")[,|\\s]+("+Wd+")[,|\\s]+("+Wd+")[,|\\s]+("+Wd+")\\s*\\)?",{CSS_UNIT:new RegExp(Wd),rgb:new RegExp("rgb"+Xd),rgba:new RegExp("rgba"+qd),hsl:new RegExp("hsl"+Xd),hsla:new RegExp("hsla"+qd),hsv:new RegExp("hsv"+Xd),hsva:new RegExp("hsva"+qd),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function Yd(e){return!!$d.CSS_UNIT.exec(e)}function Kd(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n1&&void 0!==arguments[1]?arguments[1]:{},r=i.dataBindAttr,s=void 0===r?"__data":r,a=i.objBindAttr,o=void 0===a?"__threeObj":a;return Jd(this,t),sp(n=Qd(this,t),"scene",void 0),tp(n,bp,void 0),tp(n,Sp,void 0),n.scene=e,np(bp,n,s),np(Sp,n,o),n.onRemoveObj((function(){})),n}return lp(t,e),rp(t,[{key:"onCreateObj",value:function(e){var n=this;return pp(t,"onCreateObj",this)([function(t){var i=e(t);return t[ep(Sp,n)]=i,i[ep(bp,n)]=t,n.scene.add(i),i}]),this}},{key:"onRemoveObj",value:function(e){var n=this;return pp(t,"onRemoveObj",this)([function(i,r){var s=pp(t,"getData",n)([i]);e(i,r),n.scene.remove(i),xp(i),delete s[ep(Sp,n)]}]),this}}])}(hd),Mp=function(e){return isNaN(e)?parseInt(vd(e).toHex(),16):e},Ep=function(e){return isNaN(e)?vd(e).getAlpha():1},wp=function e(){var t=new jh,n=[],i=[],r=pd;function s(e){let s=t.get(e);if(void 0===s){if(r!==pd)return r;t.set(e,s=n.push(e)-1)}return i[s%i.length]}return s.domain=function(e){if(!arguments.length)return n.slice();n=[],t=new jh;for(const i of e)t.has(i)||t.set(i,n.push(i)-1);return s},s.range=function(e){return arguments.length?(i=Array.from(e),s):i.slice()},s.unknown=function(e){return arguments.length?(r=e,s):r},s.copy=function(){return e(n,i).unknown(r)},dd.apply(s,arguments),s}(fd);function Ap(e,t,n){t&&"string"==typeof n&&e.filter((function(e){return!e[n]})).forEach((function(e){e[n]=wp(t(e))}))}var Rp=window.THREE?window.THREE:{Group:Nr,Mesh:pr,MeshLambertMaterial:Cs,Color:Pi,BufferGeometry:tr,BufferAttribute:Hi,Matrix4:kn,Vector3:un,SphereGeometry:bs,CylinderGeometry:vs,TubeGeometry:Ss,ConeGeometry:ys,Line:class extends di{constructor(e=new tr,t=new qr){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,n=[0];for(let e=1,i=t.count;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e2?-60:-30),e<3&&i(t.graphData.nodes,"z"),e<2&&i(t.graphData.nodes,"y")}},dagMode:{onChange:function(e,t){!e&&"d3"===t.forceEngine&&(t.graphData.nodes||[]).forEach((function(e){return e.fx=e.fy=e.fz=void 0}))}},dagLevelDistance:{},dagNodeFilter:{default:function(e){return!0}},onDagError:{triggerUpdate:!1},nodeRelSize:{default:4},nodeId:{default:"id"},nodeVal:{default:"val"},nodeResolution:{default:8},nodeColor:{default:"color"},nodeAutoColorBy:{},nodeOpacity:{default:.75},nodeVisibility:{default:!0},nodeThreeObject:{},nodeThreeObjectExtend:{default:!1},nodePositionUpdate:{triggerUpdate:!1},linkSource:{default:"source"},linkTarget:{default:"target"},linkVisibility:{default:!0},linkColor:{default:"color"},linkAutoColorBy:{},linkOpacity:{default:.2},linkWidth:{},linkResolution:{default:6},linkCurvature:{default:0,triggerUpdate:!1},linkCurveRotation:{default:0,triggerUpdate:!1},linkMaterial:{},linkThreeObject:{},linkThreeObjectExtend:{default:!1},linkPositionUpdate:{triggerUpdate:!1},linkDirectionalArrowLength:{default:0},linkDirectionalArrowColor:{},linkDirectionalArrowRelPos:{default:.5,triggerUpdate:!1},linkDirectionalArrowResolution:{default:8},linkDirectionalParticles:{default:0},linkDirectionalParticleSpeed:{default:.01,triggerUpdate:!1},linkDirectionalParticleWidth:{default:.5},linkDirectionalParticleColor:{},linkDirectionalParticleResolution:{default:4},forceEngine:{default:"d3"},d3AlphaMin:{default:0},d3AlphaDecay:{default:.0228,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaDecay(e)}},d3AlphaTarget:{default:0,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaTarget(e)}},d3VelocityDecay:{default:.4,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.velocityDecay(e)}},ngraphPhysics:{default:{timeStep:20,gravity:-1.2,theta:.8,springLength:30,springCoefficient:8e-4,dragCoefficient:.02}},warmupTicks:{default:0,triggerUpdate:!1},cooldownTicks:{default:1/0,triggerUpdate:!1},cooldownTime:{default:15e3,triggerUpdate:!1},onLoading:{default:function(){},triggerUpdate:!1},onFinishLoading:{default:function(){},triggerUpdate:!1},onUpdate:{default:function(){},triggerUpdate:!1},onFinishUpdate:{default:function(){},triggerUpdate:!1},onEngineTick:{default:function(){},triggerUpdate:!1},onEngineStop:{default:function(){},triggerUpdate:!1}},methods:{refresh:function(e){return e._flushObjects=!0,e._rerender(),this},d3Force:function(e,t,n){return void 0===n?e.d3ForceLayout.force(t):(e.d3ForceLayout.force(t,n),this)},d3ReheatSimulation:function(e){return e.d3ForceLayout.alpha(1),this.resetCountdown(),this},resetCountdown:function(e){return e.cntTicks=0,e.startTickTime=new Date,e.engineRunning=!0,this},tickFrame:function(e){var t,n,i,r,s="ngraph"!==e.forceEngine;return e.engineRunning&&function(){++e.cntTicks>e.cooldownTicks||new Date-e.startTickTime>e.cooldownTime||s&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()0){var f=o.x-a.x,m=o.y-a.y||0,g=(new Rp.Vector3).subVectors(h,c),_=g.clone().multiplyScalar(l).cross(0!==f||0!==m?new Rp.Vector3(0,0,1):new Rp.Vector3(0,1,0)).applyAxisAngle(g.normalize(),p).add((new Rp.Vector3).addVectors(c,h).divideScalar(2));u=new Rp.QuadraticBezierCurve3(c,_,h)}else{var v=70*l,y=-p,x=y+Math.PI/2;u=new Rp.CubicBezierCurve3(c,new Rp.Vector3(v*Math.cos(x),v*Math.sin(x),0).add(c),new Rp.Vector3(v*Math.cos(y),v*Math.sin(y),0).add(c),h)}t.__curve=u}else t.__curve=null}}e.linkDataMapper.entries().forEach((function(t){var i=dp(t,2),r=i[0],l=i[1];if(l){var u=s?r:e.layout.getLinkPosition(e.layout.graph.getLink(r.source,r.target).id),c=u[s?"source":"from"],h=u[s?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){o(r);var d=a(r);if(!e.linkPositionUpdate||!e.linkPositionUpdate(d?l.children[1]:l,{start:{x:c.x,y:c.y,z:c.z},end:{x:h.x,y:h.y,z:h.z}},r)||d){var p=30,f=r.__curve,m=l.children.length?l.children[0]:l;if("Line"===m.type){if(f){var g=f.getPoints(p);m.geometry.getAttribute("position").array.length!==3*g.length&&m.geometry[Np]("position",new Rp.BufferAttribute(new Float32Array(3*g.length),3)),m.geometry.setFromPoints(g)}else{var _=m.geometry.getAttribute("position");_&&_.array&&6===_.array.length||m.geometry[Np]("position",_=new Rp.BufferAttribute(new Float32Array(6),3)),_.array[0]=c.x,_.array[1]=c.y||0,_.array[2]=c.z||0,_.array[3]=h.x,_.array[4]=h.y||0,_.array[5]=h.z||0,_.needsUpdate=!0}m.geometry.computeBoundingSphere()}else if("Mesh"===m.type)if(f){m.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(m.position.set(0,0,0),m.rotation.set(0,0,0),m.scale.set(1,1,1));var v=Math.ceil(10*n(r))/10/2,y=new Rp.TubeGeometry(f,p,v,e.linkResolution,!1);m.geometry.dispose(),m.geometry=y}else{if(!m.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var x=Math.ceil(10*n(r))/10/2,b=new Rp.CylinderGeometry(x,x,1,e.linkResolution,1,!1);b[Pp]((new Rp.Matrix4).makeTranslation(0,.5,0)),b[Pp]((new Rp.Matrix4).makeRotationX(Math.PI/2)),m.geometry.dispose(),m.geometry=b}var S=new Rp.Vector3(c.x,c.y||0,c.z||0),T=new Rp.Vector3(h.x,h.y||0,h.z||0),M=S.distanceTo(T);m.position.x=S.x,m.position.y=S.y,m.position.z=S.z,m.scale.z=M,m.parent.localToWorld(T),m.lookAt(T)}}}}}))}(),t=Hh(e.linkDirectionalArrowRelPos),n=Hh(e.linkDirectionalArrowLength),i=Hh(e.nodeVal),e.arrowDataMapper.entries().forEach((function(r){var a=dp(r,2),o=a[0],l=a[1];if(l){var u=s?o:e.layout.getLinkPosition(e.layout.graph.getLink(o.source,o.target).id),c=u[s?"source":"from"],h=u[s?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){var d=Math.cbrt(Math.max(0,i(c)||1))*e.nodeRelSize,p=Math.cbrt(Math.max(0,i(h)||1))*e.nodeRelSize,f=n(o),m=t(o),g=o.__curve?function(e){return o.__curve.getPoint(e)}:function(e){var t=function(e,t,n,i){return t[e]+(n[e]-t[e])*i||0};return{x:t("x",c,h,e),y:t("y",c,h,e),z:t("z",c,h,e)}},_=o.__curve?o.__curve.getLength():Math.sqrt(["x","y","z"].map((function(e){return Math.pow((h[e]||0)-(c[e]||0),2)})).reduce((function(e,t){return e+t}),0)),v=d+f+(_-d-p-f)*m,y=g(v/_),x=g((v-f)/_);["x","y","z"].forEach((function(e){return l.position[e]=x[e]}));var b=ip(Rp.Vector3,fp(["x","y","z"].map((function(e){return y[e]}))));l.parent.localToWorld(b),l.lookAt(b)}}})),r=Hh(e.linkDirectionalParticleSpeed),e.graphData.links.forEach((function(t){var n=e.particlesDataMapper.getObj(t),i=n&&n.children,a=t.__singleHopPhotonsObj&&t.__singleHopPhotonsObj.children;if(a&&a.length||i&&i.length){var o=s?t:e.layout.getLinkPosition(e.layout.graph.getLink(t.source,t.target).id),l=o[s?"source":"from"],u=o[s?"target":"to"];if(l&&u&&l.hasOwnProperty("x")&&u.hasOwnProperty("x")){var c=r(t),h=t.__curve?function(e){return t.__curve.getPoint(e)}:function(e){var t=function(e,t,n,i){return t[e]+(n[e]-t[e])*i||0};return{x:t("x",l,u,e),y:t("y",l,u,e),z:t("z",l,u,e)}};[].concat(fp(i||[]),fp(a||[])).forEach((function(e,t){var n="singleHopPhotons"===e.parent.__linkThreeObjType;if(e.hasOwnProperty("__progressRatio")||(e.__progressRatio=n?0:t/i.length),e.__progressRatio+=c,e.__progressRatio>=1){if(n)return e.parent.remove(e),void xp(e);e.__progressRatio=e.__progressRatio%1}var r=e.__progressRatio,s=h(r);["x","y","z"].forEach((function(t){return e.position[t]=s[t]}))}))}}})),this},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){var n=new Rp.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var i=Hh(e.linkDirectionalParticleWidth),r=Math.ceil(10*i(t))/10/2,s=e.linkDirectionalParticleResolution,a=new Rp.SphereGeometry(r,s,s),o=Hh(e.linkColor),l=Hh(e.linkDirectionalParticleColor)(t)||o(t)||"#f0f0f0",u=new Rp.Color(Mp(l)),c=3*e.linkOpacity,h=new Rp.MeshLambertMaterial({color:u,transparent:!0,opacity:c});t.__singleHopPhotonsObj.add(new Rp.Mesh(a,h))}return this},getGraphBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0};if(!e.initialised)return null;var n=function e(n){var i=[];if(n.geometry){n.geometry.computeBoundingBox();var r=new Rp.Box3;r.copy(n.geometry.boundingBox).applyMatrix4(n.matrixWorld),i.push(r)}return i.concat.apply(i,fp((n.children||[]).filter((function(e){return!e.hasOwnProperty("__graphObjType")||"node"===e.__graphObjType&&t(e.__data)})).map(e)))}(e.graphScene);return n.length?Object.assign.apply(Object,fp(["x","y","z"].map((function(e){return sp({},e,[$h(n,(function(t){return t.min[e]})),qh(n,(function(t){return t.max[e]}))])})))):null}},stateInit:function(){return{d3ForceLayout:Pc().force("link",Qu()).force("charge",Dc()).force("center",Su()).force("dagRadial",null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new Tp(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new Tp(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new Tp(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new Tp(e,{objBindAttr:"__photonsObj"})},update:function(e,t){var n=function(e){return e.some((function(e){return t.hasOwnProperty(e)}))};if(e.engineRunning=!1,"function"==typeof e.onUpdate&&e.onUpdate(),null!==e.nodeAutoColorBy&&n(["nodeAutoColorBy","graphData","nodeColor"])&&Ap(e.graphData.nodes,Hh(e.nodeAutoColorBy),e.nodeColor),null!==e.linkAutoColorBy&&n(["linkAutoColorBy","graphData","linkColor"])&&Ap(e.graphData.links,Hh(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){var i=Hh(e.nodeThreeObject),r=Hh(e.nodeThreeObjectExtend),s=Hh(e.nodeVal),a=Hh(e.nodeColor),o=Hh(e.nodeVisibility),l={},u={};(e._flushObjects||n(["nodeThreeObject","nodeThreeObjectExtend"]))&&e.nodeDataMapper.clear(),e.nodeDataMapper.onCreateObj((function(t){var n,s=i(t),a=r(t);return s&&e.nodeThreeObject===s&&(s=s.clone()),s&&!a?n=s:((n=new Rp.Mesh).__graphDefaultObj=!0,s&&a&&n.add(s)),n.__graphObjType="node",n})).onUpdateObj((function(t,n){if(t.__graphDefaultObj){var i=s(n)||1,r=Math.cbrt(i)*e.nodeRelSize,o=e.nodeResolution;t.geometry.type.match(/^Sphere(Buffer)?Geometry$/)&&t.geometry.parameters.radius===r&&t.geometry.parameters.widthSegments===o||(l.hasOwnProperty(i)||(l[i]=new Rp.SphereGeometry(r,o,o)),t.geometry.dispose(),t.geometry=l[i]);var c=a(n),h=new Rp.Color(Mp(c||"#ffffaa")),d=e.nodeOpacity*Ep(c);"MeshLambertMaterial"===t.material.type&&t.material.color.equals(h)&&t.material.opacity===d||(u.hasOwnProperty(c)||(u[c]=new Rp.MeshLambertMaterial({color:h,transparent:!0,opacity:d})),t.material.dispose(),t.material=u[c])}})).digest(e.graphData.nodes.filter(o))}if(e._flushObjects||n(["graphData","linkThreeObject","linkThreeObjectExtend","linkMaterial","linkColor","linkWidth","linkVisibility","linkResolution","linkOpacity","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution"])){var c=Hh(e.linkThreeObject),h=Hh(e.linkThreeObjectExtend),d=Hh(e.linkMaterial),p=Hh(e.linkVisibility),f=Hh(e.linkColor),m=Hh(e.linkWidth),g={},_={},v={},y=e.graphData.links.filter(p);if((e._flushObjects||n(["linkThreeObject","linkThreeObjectExtend","linkWidth"]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj((function(e){var t=e.__data&&e.__data.__singleHopPhotonsObj;t&&(t.parent.remove(t),xp(t),delete e.__data.__singleHopPhotonsObj)})).onCreateObj((function(t){var n,i,r=c(t),s=h(t);if(r&&e.linkThreeObject===r&&(r=r.clone()),!r||s)if(!!m(t))n=new Rp.Mesh;else{var a=new Rp.BufferGeometry;a[Np]("position",new Rp.BufferAttribute(new Float32Array(6),3)),n=new Rp.Line(a)}return r?s?((i=new Rp.Group).__graphDefaultObj=!0,i.add(n),i.add(r)):i=r:(i=n).__graphDefaultObj=!0,i.renderOrder=10,i.__graphObjType="link",i})).onUpdateObj((function(t,n){if(t.__graphDefaultObj){var i=t.children.length?t.children[0]:t,r=Math.ceil(10*m(n))/10,s=!!r;if(s){var a=r/2,o=e.linkResolution;if(!i.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||i.geometry.parameters.radiusTop!==a||i.geometry.parameters.radialSegments!==o){if(!g.hasOwnProperty(r)){var l=new Rp.CylinderGeometry(a,a,1,o,1,!1);l[Pp]((new Rp.Matrix4).makeTranslation(0,.5,0)),l[Pp]((new Rp.Matrix4).makeRotationX(Math.PI/2)),g[r]=l}i.geometry.dispose(),i.geometry=g[r]}}var u=d(n);if(u)i.material=u;else{var c=f(n),h=new Rp.Color(Mp(c||"#f0f0f0")),p=e.linkOpacity*Ep(c),y=s?"MeshLambertMaterial":"LineBasicMaterial";if(i.material.type!==y||!i.material.color.equals(h)||i.material.opacity!==p){var x=s?_:v;x.hasOwnProperty(c)||(x[c]=new Rp[y]({color:h,transparent:p<1,opacity:p,depthWrite:p>=1})),i.material.dispose(),i.material=x[c]}}}})).digest(y),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){var x=Hh(e.linkDirectionalArrowLength),b=Hh(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj((function(){var e=new Rp.Mesh(void 0,new Rp.MeshLambertMaterial({transparent:!0}));return e.__linkThreeObjType="arrow",e})).onUpdateObj((function(t,n){var i=x(n),r=e.linkDirectionalArrowResolution;if(!t.geometry.type.match(/^Cone(Buffer)?Geometry$/)||t.geometry.parameters.height!==i||t.geometry.parameters.radialSegments!==r){var s=new Rp.ConeGeometry(.25*i,i,r);s.translate(0,i/2,0),s.rotateX(Math.PI/2),t.geometry.dispose(),t.geometry=s}var a=b(n)||f(n)||"#f0f0f0";t.material.color=new Rp.Color(Mp(a)),t.material.opacity=3*e.linkOpacity*Ep(a)})).digest(y.filter(x))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){var S=Hh(e.linkDirectionalParticles),T=Hh(e.linkDirectionalParticleWidth),M=Hh(e.linkDirectionalParticleColor),E={},w={};e.particlesDataMapper.onCreateObj((function(){var e=new Rp.Group;return e.__linkThreeObjType="photons",e.__photonDataMapper=new Tp(e),e})).onUpdateObj((function(t,n){var i,r=Math.round(Math.abs(S(n))),s=!!t.children.length&&t.children[0],a=Math.ceil(10*T(n))/10/2,o=e.linkDirectionalParticleResolution;s&&s.geometry.parameters.radius===a&&s.geometry.parameters.widthSegments===o?i=s.geometry:(w.hasOwnProperty(a)||(w[a]=new Rp.SphereGeometry(a,o,o)),i=w[a],s&&s.geometry.dispose());var l,u=M(n)||f(n)||"#f0f0f0",c=new Rp.Color(Mp(u)),h=3*e.linkOpacity;s&&s.material.color.equals(c)&&s.material.opacity===h?l=s.material:(E.hasOwnProperty(u)||(E[u]=new Rp.MeshLambertMaterial({color:c,transparent:!0,opacity:h})),l=E[u],s&&s.material.dispose()),t.__photonDataMapper.id((function(e){return e.idx})).onCreateObj((function(){return new Rp.Mesh(i,l)})).onUpdateObj((function(e){e.geometry=i,e.material=l})).digest(fp(new Array(r)).map((function(e,t){return{idx:t}})))})).digest(y.filter(S))}}if(e._flushObjects=!1,n(["graphData","nodeId","linkSource","linkTarget","numDimensions","forceEngine","dagMode","dagNodeFilter","dagLevelDistance"])){e.engineRunning=!1,e.graphData.links.forEach((function(t){t.source=t[e.linkSource],t.target=t[e.linkTarget]}));var A,R="ngraph"!==e.forceEngine;if(R){(A=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);var C=e.d3ForceLayout.force("link");C&&C.id((function(t){return t[e.nodeId]})).links(e.graphData.links);var N=e.dagMode&&function(e,t){var n=e.nodes,i=e.links,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=r.nodeFilter,a=void 0===s?function(){return!0}:s,o=r.onLoopError,l=void 0===o?function(e){throw"Invalid DAG structure! Found cycle in node path: ".concat(e.join(" -> "),".")}:o,u={};n.forEach((function(e){return u[t(e)]={data:e,out:[],depth:-1,skip:!a(e)}})),i.forEach((function(e){var n=e.source,i=e.target,r=l(n),s=l(i);if(!u.hasOwnProperty(r))throw"Missing source node with id: ".concat(r);if(!u.hasOwnProperty(s))throw"Missing target node with id: ".concat(s);var a=u[r],o=u[s];function l(e){return"object"===gp(e)?t(e):e}a.out.push(o)}));var c=[];return function e(n){for(var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=function(){var s=n[a];if(-1!==i.indexOf(s)){var o=[].concat(fp(i.slice(i.indexOf(s))),[s]).map((function(e){return t(e.data)}));return c.some((function(e){return e.length===o.length&&e.every((function(e,t){return e===o[t]}))}))||(c.push(o),l(o)),1}r>s.depth&&(s.depth=r,e(s.out,[].concat(fp(i),[s]),r+(s.skip?0:1)))},a=0,o=n.length;a1&&(c.vy+=d*m),s>2&&(c.vz+=p*m)}}function c(){if(r){var t,n=r.length;for(a=new Array(n),o=new Array(n),t=0;t[1,2,3].includes(e)))||2,c()},u.strength=function(e){return arguments.length?(l="function"==typeof e?e:$u(+e),c(),u):l},u.radius=function(t){return arguments.length?(e="function"==typeof t?t:$u(+t),c(),u):e},u.x=function(e){return arguments.length?(t=+e,u):t},u.y=function(e){return arguments.length?(n=+e,u):n},u.z=function(e){return arguments.length?(i=+e,u):i},u}((function(t){var n=N[t[e.nodeId]]||-1;return("radialin"===e.dagMode?P-n:n)*D})).strength((function(t){return e.dagNodeFilter(t)?1:0})):null)}else{var O=Cp.graph();e.graphData.nodes.forEach((function(t){O.addNode(t[e.nodeId])})),e.graphData.links.forEach((function(e){O.addLink(e.source,e.target)})),A=Cp.forcelayout(O,function(e){for(var t=1;t0&&e.d3ForceLayout.alpha()2&&void 0!==arguments[2]&&arguments[2],n=function(n){function i(){var n;Jd(this,i);for(var r=arguments.length,s=new Array(r),a=0;a1&&void 0!==arguments[1]?arguments[1]:Object);return Object.keys(e()).forEach((function(e){return n.prototype[e]=function(){var t,n=(t=this.__kapsuleInstance)[e].apply(t,arguments);return n===this.__kapsuleInstance?this:n}})),n}(Dp,(window.THREE?window.THREE:{Group:Nr}).Group,!0);const Lp=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveMap","envMap","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"];class Ip{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Lp,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:n,material:i,object:r}=e;if(t={material:this.getMaterialData(i),geometry:{id:n.id,attributes:this.getAttributesData(n.attributes),indexVersion:n.index?n.index.version:null,drawRange:{start:n.drawRange.start,count:n.drawRange.count}},worldMatrix:r.matrixWorld.clone()},r.center&&(t.center=r.center.clone()),r.morphTargetInfluences&&(t.morphTargetInfluences=r.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),t.material.transmission>0){const{width:n,height:i}=e.context;t.bufferWidth=n,t.bufferHeight=i}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const n in e){const i=e[n];t[n]={version:i.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return null!==e.renderer.nodes.modelViewMatrix||null!==e.renderer.nodes.modelNormalViewMatrix}getMaterialData(e){const t={};for(const n of this.refreshUniforms){const i=e[n];null!=i&&("object"==typeof i&&void 0!==i.clone?!0===i.isTexture?t[n]={id:i.id,version:i.version}:t[n]=i.clone():t[n]=i)}return t}equals(e){const{object:t,material:n,geometry:i}=e,r=this.getRenderObjectData(e);if(!0!==r.worldMatrix.equals(t.matrixWorld))return r.worldMatrix.copy(t.matrixWorld),!1;const s=r.material;for(const e in s){const t=s[e],i=n[e];if(void 0!==t.equals){if(!1===t.equals(i))return t.copy(i),!1}else if(!0===i.isTexture){if(t.id!==i.id||t.version!==i.version)return t.id=i.id,t.version=i.version,!1}else if(t!==i)return s[e]=i,!1}if(s.transmission>0){const{width:t,height:n}=e.context;if(r.bufferWidth!==t||r.bufferHeight!==n)return r.bufferWidth=t,r.bufferHeight=n,!1}const a=r.geometry,o=i.attributes,l=a.attributes,u=Object.keys(l),c=Object.keys(o);if(a.id!==i.id)return a.id=i.id,!1;if(u.length!==c.length)return r.geometry.attributes=this.getAttributesData(o),!1;for(const e of u){const t=l[e],n=o[e];if(void 0===n)return delete l[e],!1;if(t.version!==n.version)return t.version=n.version,!1}const h=i.index,d=a.indexVersion,p=h?h.version:null;if(d!==p)return a.indexVersion=p,!1;if(a.drawRange.start!==i.drawRange.start||a.drawRange.count!==i.drawRange.count)return a.drawRange.start=i.drawRange.start,a.drawRange.count=i.drawRange.count,!1;if(r.morphTargetInfluences){let e=!1;for(let n=0;n>>16,2246822507),n^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&i)+(n>>>0)}const Fp=e=>Op(e),Bp=(...e)=>Op(e);function kp(e,t=!1){const n=[];!0===e.isNode&&(n.push(e.id),e=e.getSelf());for(const{property:i,childNode:r}of zp(e))n.push(Op(i.slice(0,-4)),r.getCacheKey(t));return Op(n)}function*zp(e,t=!1){for(const n in e){if(!0===n.startsWith("_"))continue;const i=e[n];if(!0===Array.isArray(i))for(let e=0;ee.charCodeAt(0))).buffer):null;var i}function Wp(e){let t=Vp.get(e);return void 0===t&&(t={},Vp.set(e,t)),t}const Xp="vertex",qp="none",$p="frame",Yp="render",Kp="object",Zp="readOnly",Qp="writeOnly",Jp="readWrite",ef=["setup","analyze","generate"],tf=["fragment","vertex","compute"],nf=["x","y","z","w"];let rf=0;class sf extends Tt{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=qp,this.updateBeforeType=qp,this.updateAfterType=qp,this.uuid=Lt.generateUUID(),this.version=0,this.global=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:rf++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,$p)}onRenderUpdate(e){return this.onUpdate(e,Yp)}onObjectUpdate(e){return this.onUpdate(e,Kp)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of zp(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return!0!==(e=e||this.version!==this._cacheKeyVersion)&&null!==this._cacheKey||(this._cacheKey=Bp(kp(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}setup(e){const t=e.getNodeProperties(this);let n=0;for(const e of this.getChildren())t["node"+n++]=e;return t.outputNode||null}analyze(e){if(1===e.increaseUsage(this)){const t=e.getNodeProperties(this);for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e)}}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);if(n&&!0===n.isNode)return n.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const n=this.getShared(e);if(this!==n)return n.build(e,t);e.addNode(this),e.addChain(this);let i=null;const r=e.getBuildStage();if("setup"===r){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0;const n=this.setup(e),i=n&&!0===n.isNode;for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e);i&&n.build(e),t.outputNode=n}}else if("analyze"===r)this.analyze(e);else if("generate"===r){if(1===this.generate.length){const n=this.getNodeType(e),r=e.getDataFromNode(this);i=r.snippet,void 0===i?(i=this.generate(e)||"",r.snippet=i):void 0!==r.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),i=e.format(i,n,t)}else i=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),i}getSerializeChildren(){return zp(this)}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:i,index:r,childNode:s}of t)void 0!==r?(void 0===n[i]&&(n[i]=Number.isInteger(r)?[]:{}),n[i][r]=s.toJSON(e.meta).uuid):n[i]=s.toJSON(e.meta).uuid;Object.keys(n).length>0&&(e.inputNodes=n)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const i=[];for(const r of e.inputNodes[n])i.push(t[r]);this[n]=i}else if("object"==typeof e.inputNodes[n]){const i={};for(const r in e.inputNodes[n]){const s=e.inputNodes[n][r];i[r]=t[s]}this[n]=i}else{const i=e.inputNodes[n];this[n]=t[i]}}}toJSON(e){const{uuid:t,type:n}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function s(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:n,meta:e,metadata:{version:4.6,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=s(e.textures),n=s(e.images),i=s(e.nodes);t.length>0&&(r.textures=t),n.length>0&&(r.images=n),i.length>0&&(r.nodes=i)}return r}}class af extends sf{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}generate(e){return`${this.node.build(e)}[ ${this.indexNode.build(e,"uint")} ]`}}class of extends sf{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const i of this.convertTo.split("|"))null!==n&&e.getTypeLength(t)!==e.getTypeLength(i)||(n=i);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const n=this.node,i=this.getNodeType(e),r=n.build(e,i);return e.format(r,i,t)}}class lf extends sf{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const n=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,n,t);if("void"!==n&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,n),s=e.getVarFromNode(this,null,n),a=e.getPropertyName(s);return e.addLineFlowCode(`${a} = ${r}`,this),i.snippet=r,i.propertyName=a,e.format(i.propertyName,n,t)}}return super.build(e,t)}}class uf extends lf{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce(((t,n)=>t+e.getTypeLength(n.getNodeType(e))),0))}generate(e,t){const n=this.getNodeType(e),i=this.nodes,r=e.getComponentType(n),s=[];for(const t of i){let n=t.build(e);const i=e.getComponentType(t.getNodeType(e));i!==r&&(n=e.format(n,i,r)),s.push(n)}const a=`${e.getType(n)}( ${s.join(", ")} )`;return e.format(a,n,t)}}const cf=nf.join("");class hf extends sf{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(nf.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}generate(e,t){const n=this.node,i=e.getTypeLength(n.getNodeType(e));let r=null;if(i>1){let s=null;this.getVectorLength()>=i&&(s=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=n.build(e,s);r=this.components.length===i&&this.components===cf.slice(0,this.components.length)?e.format(a,s,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else r=n.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class df extends lf{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:i}=this,r=this.getNodeType(e),s=e.getComponentType(i.getNodeType(e)),a=e.getTypeFromLength(n.length,s),o=i.build(e,a),l=t.build(e,r),u=e.getTypeLength(r),c=[];for(let e=0;ee.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),Sf=e=>bf(e).split("").sort().join(""),Tf={setup(e,t){const n=t.shift();return e(qf(n),...t)},get(e,t,n){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(vf.assign(n,...e),n);if(yf.has(t)){const i=yf.get(t);return e.isStackNode?(...e)=>n.add(i(...e)):(...e)=>i(n,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&yf.has(t.slice(0,t.length-6))){const i=yf.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>n.assign(e[0],i(...e)):(...e)=>n.assign(i(n,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=bf(t),Xf(new hf(n,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Sf(t.slice(3).toLowerCase()),n=>Xf(new df(e,t,n));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Sf(t.slice(4).toLowerCase()),()=>Xf(new pf(Xf(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Xf(new hf(e,t));if(!0===/^\d+$/.test(t))return Xf(new af(n,new gf(Number(t),"uint")));if(!0===/^get$/.test(t))return e=>Xf(new _f(n,e))}return Reflect.get(e,t,n)},set:(e,t,n,i)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,n,i):(i[t].assign(n),!0)},Mf=new WeakMap,Ef=new WeakMap,wf=function(e,t=null){for(const n in e)e[n]=Xf(e[n],t);return e},Af=function(e,t=null){const n=e.length;for(let i=0;iXf(null!==i?Object.assign(e,i):e);return null===t?(...t)=>r(new e(...$f(t))):null!==n?(n=Xf(n),(...i)=>r(new e(t,...$f(i),n))):(...n)=>r(new e(t,...$f(n)))},Cf=function(e,...t){return Xf(new e(...$f(t)))};class Nf extends sf{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:n}=this,i=e.getNodeProperties(t);if(i.onceOutput)return i.onceOutput;let r=null;if(t.layout){let i=Ef.get(e.constructor);void 0===i&&(i=new WeakMap,Ef.set(e.constructor,i));let s=i.get(t);void 0===s&&(s=Xf(e.buildFunctionNode(t)),i.set(t,s)),e.addInclude(s),r=Xf(s.call(n))}else{const i=t.jsFunc,s=null!==n||i.length>1?i(n||[],e):i(e);r=Xf(s)}return t.once&&(i.onceOutput=r),r}getOutputNode(e){const t=e.getNodeProperties(this);return null===t.outputNode&&(t.outputNode=this.setupOutput(e)),t.outputNode}setup(e){return this.getOutputNode(e)}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}generate(e,t){return this.getOutputNode(e).build(e,t)}}class Pf extends sf{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}call(e=null){return qf(e),Xf(new Nf(this,e))}setup(){return this.call()}}const Df=[!1,!0],Uf=[0,1,2,3],Lf=[-1,-2],If=[.5,1.5,1/3,1e-6,1e6,Math.PI,2*Math.PI,1/Math.PI,2/Math.PI,1/(2*Math.PI),Math.PI/2],Of=new Map;for(const e of Df)Of.set(e,new gf(e));const Ff=new Map;for(const e of Uf)Ff.set(e,new gf(e,"uint"));const Bf=new Map([...Ff].map((e=>new gf(e.value,"int"))));for(const e of Lf)Bf.set(e,new gf(e,"int"));const kf=new Map([...Bf].map((e=>new gf(e.value))));for(const e of If)kf.set(e,new gf(e));for(const e of If)kf.set(-e,new gf(-e));const zf={bool:Of,uint:Ff,ints:Bf,float:kf},Gf=new Map([...Of,...kf]),Vf=(e,t)=>Gf.has(e)?Gf.get(e):!0===e.isNode?e:new gf(e,t),Hf=function(e,t=null){return(...n)=>{if((0===n.length||!["bool","float","int","uint"].includes(e)&&n.every((e=>"object"!=typeof e)))&&(n=[jp(e,...n)]),1===n.length&&null!==t&&t.has(n[0]))return Xf(t.get(n[0]));if(1===n.length){const t=Vf(n[0],e);return(e=>{try{return e.getNodeType()}catch(e){return}})(t)===e?Xf(t):Xf(new of(t,e))}const i=n.map((e=>Vf(e)));return Xf(new uf(i,e))}},jf=e=>"object"==typeof e&&null!==e?e.value:e;function Wf(e,t){return new Proxy(new Pf(e,t),Tf)}const Xf=(e,t=null)=>function(e,t=null){const n=Hp(e);if("node"===n){let t=Mf.get(e);return void 0===t&&(t=new Proxy(e,Tf),Mf.set(e,t),Mf.set(t,t)),t}return null===t&&("float"===n||"boolean"===n)||n&&"shader"!==n&&"string"!==n?Xf(Vf(e,t)):"shader"===n?Zf(e):e}(e,t),qf=(e,t=null)=>new wf(e,t),$f=(e,t=null)=>new Af(e,t),Yf=(...e)=>new Rf(...e),Kf=(...e)=>new Cf(...e),Zf=(e,t)=>{const n=new Wf(e,t),i=(...e)=>{let t;return qf(e),t=e[0]&&e[0].isNode?[...e]:e[0],n.call(t)};return i.shaderNode=n,i.setLayout=e=>(n.setLayout(e),i),i.once=()=>(n.once=!0,i),i};xf("toGlobal",(e=>(e.global=!0,e)));const Qf=e=>{vf=e},Jf=()=>vf,em=(...e)=>vf.If(...e);xf("append",(function(e){return vf&&vf.add(e),e}));const tm=new Hf("color"),nm=new Hf("float",zf.float),im=new Hf("int",zf.ints),rm=new Hf("uint",zf.uint),sm=new Hf("bool",zf.bool),am=new Hf("vec2"),om=new Hf("ivec2"),lm=new Hf("uvec2"),um=new Hf("bvec2"),cm=new Hf("vec3"),hm=new Hf("ivec3"),dm=new Hf("uvec3"),pm=new Hf("bvec3"),fm=new Hf("vec4"),mm=new Hf("ivec4"),gm=new Hf("uvec4"),_m=new Hf("bvec4"),vm=new Hf("mat2"),ym=new Hf("mat3"),xm=new Hf("mat4");xf("toColor",tm),xf("toFloat",nm),xf("toInt",im),xf("toUint",rm),xf("toBool",sm),xf("toVec2",am),xf("toIVec2",om),xf("toUVec2",lm),xf("toBVec2",um),xf("toVec3",cm),xf("toIVec3",hm),xf("toUVec3",dm),xf("toBVec3",pm),xf("toVec4",fm),xf("toIVec4",mm),xf("toUVec4",gm),xf("toBVec4",_m),xf("toMat2",vm),xf("toMat3",ym),xf("toMat4",xm);xf("element",Yf(af)),xf("convert",((e,t)=>Xf(new of(Xf(e),t))));class bm extends lf{static get type(){return"ArrayNode"}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}xf("toArray",((e,t)=>((...e)=>{let t;if(1===e.length){const n=e[0];t=new bm(null,n.length,n)}else{const n=e[0],i=e[1];t=new bm(n,i)}return Xf(t)})(Array(t).fill(e))));class Sm extends sf{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1){super("string"),this.name=e,this.shared=t,this.order=n,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const Tm=e=>new Sm(e),Mm=(e,t=0)=>new Sm(e,!0,t),Em=Mm("frame"),wm=Mm("render"),Am=Tm("object");class Rm extends ff{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Am}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const n=this.getSelf();return e=e.bind(n),super.onUpdate((t=>{const i=e(t,n);void 0!==i&&(this.value=i)}),t)}generate(e,t){const n=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const s=r.getInputType(e),a=e.getUniformFromNode(r,s,e.shaderStage,this.name||e.context.label),o=e.getPropertyName(a);return void 0!==e.context.label&&delete e.context.label,e.format(o,n,t)}}const Cm=(e,t)=>{const n=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e),i=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return Xf(new Rm(i,n))};class Nm extends sf{static get type(){return"PropertyNode"}constructor(e,t=null,n=!1){super(e),this.name=t,this.varying=n,this.isPropertyNode=!0}getHash(e){return this.name||super.getHash(e)}isGlobal(){return!0}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Pm=(e,t)=>Xf(new Nm(e,t)),Dm=(e,t)=>Xf(new Nm(e,t,!0)),Um=Kf(Nm,"vec4","DiffuseColor"),Lm=Kf(Nm,"vec3","EmissiveColor"),Im=Kf(Nm,"float","Roughness"),Om=Kf(Nm,"float","Metalness"),Fm=Kf(Nm,"float","Clearcoat"),Bm=Kf(Nm,"float","ClearcoatRoughness"),km=Kf(Nm,"vec3","Sheen"),zm=Kf(Nm,"float","SheenRoughness"),Gm=Kf(Nm,"float","Iridescence"),Vm=Kf(Nm,"float","IridescenceIOR"),Hm=Kf(Nm,"float","IridescenceThickness"),jm=Kf(Nm,"float","AlphaT"),Wm=Kf(Nm,"float","Anisotropy"),Xm=Kf(Nm,"vec3","AnisotropyT"),qm=Kf(Nm,"vec3","AnisotropyB"),$m=Kf(Nm,"color","SpecularColor"),Ym=Kf(Nm,"float","SpecularF90"),Km=Kf(Nm,"float","Shininess"),Zm=Kf(Nm,"vec4","Output"),Qm=Kf(Nm,"float","dashSize"),Jm=Kf(Nm,"float","gapSize"),eg=Kf(Nm,"float","IOR"),tg=Kf(Nm,"float","Transmission"),ng=Kf(Nm,"float","Thickness"),ig=Kf(Nm,"float","AttenuationDistance"),rg=Kf(Nm,"color","AttenuationColor"),sg=Kf(Nm,"float","Dispersion");class ag extends lf{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const n=e.getTypeLength(t.node.getNodeType(e));return nf.join("").slice(0,n)!==t.components}return!1}generate(e,t){const{targetNode:n,sourceNode:i}=this,r=this.needsSplitAssign(e),s=n.getNodeType(e),a=n.context({assign:!0}).build(e),o=i.build(e,s),l=i.getNodeType(e),u=e.getDataFromNode(this);let c;if(!0===u.initialized)"void"!==t&&(c=a);else if(r){const i=e.getVarFromNode(this,null,s),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${o}`,this);const l=n.node.context({assign:!0}).build(e);for(let t=0;t{const i=n.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r))for(let e=0;e(t=t.length>1||t[0]&&!0===t[0].isNode?$f(t):qf(t[0]),Xf(new og(Xf(e),t)))));class lg extends lf{static get type(){return"OperatorNode"}constructor(e,t,n,...i){if(super(),i.length>0){let r=new lg(e,t,n);for(let t=0;t>"===n||"<<"===n)return e.getIntegerType(s);if("!"===n||"=="===n||"&&"===n||"||"===n||"^^"===n)return"bool";if("<"===n||">"===n||"<="===n||">="===n){const n=t?e.getTypeLength(t):Math.max(e.getTypeLength(s),e.getTypeLength(a));return n>1?`bvec${n}`:"bool"}if(e.isMatrix(s)){if("float"===a)return s;if(e.isVector(a))return e.getVectorFromMatrix(s);if(e.isMatrix(a))return s}else if(e.isMatrix(a)){if("float"===s)return a;if(e.isVector(s))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(s)?a:s}generate(e,t){const n=this.op,i=this.aNode,r=this.bNode,s=this.getNodeType(e,t);let a=null,o=null;"void"!==s?(a=i.getNodeType(e),o=void 0!==r?r.getNodeType(e):null,"<"===n||">"===n||"<="===n||">="===n||"=="===n?e.isVector(a)?o=a:a!==o&&(a=o="float"):">>"===n||"<<"===n?(a=s,o=e.changeComponentType(o,"uint")):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=s):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=s:o=s):a=o=s;const l=i.build(e,a),u=void 0!==r?r.build(e,o):null,c=e.getTypeLength(t),h=e.getFunctionOperator(n);return"void"!==t?"<"===n&&c>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThan",t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} < ${u} )`,s,t):"<="===n&&c>1?e.useComparisonMethod?e.format(`${e.getMethod("lessThanEqual",t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} <= ${u} )`,s,t):">"===n&&c>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThan",t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} > ${u} )`,s,t):">="===n&&c>1?e.useComparisonMethod?e.format(`${e.getMethod("greaterThanEqual",t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} >= ${u} )`,s,t):"!"===n||"~"===n?e.format(`(${n}${l})`,a,t):h?e.format(`${h}( ${l}, ${u} )`,s,t):e.isMatrix(a)&&"float"===o?e.format(`( ${u} ${n} ${l} )`,s,t):"float"===a&&e.isMatrix(o)?e.format(`${l} ${n} ${u}`,s,t):e.format(`( ${l} ${n} ${u} )`,s,t):"void"!==a?h?e.format(`${h}( ${l}, ${u} )`,s,t):e.isMatrix(a)&&"float"===o?e.format(`${u} ${n} ${l}`,s,t):e.format(`${l} ${n} ${u}`,s,t):void 0}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const ug=Yf(lg,"+"),cg=Yf(lg,"-"),hg=Yf(lg,"*"),dg=Yf(lg,"/"),pg=Yf(lg,"%"),fg=Yf(lg,"=="),mg=Yf(lg,"!="),gg=Yf(lg,"<"),_g=Yf(lg,">"),vg=Yf(lg,"<="),yg=Yf(lg,">="),xg=Yf(lg,"&&"),bg=Yf(lg,"||"),Sg=Yf(lg,"!"),Tg=Yf(lg,"^^"),Mg=Yf(lg,"&"),Eg=Yf(lg,"~"),wg=Yf(lg,"|"),Ag=Yf(lg,"^"),Rg=Yf(lg,"<<"),Cg=Yf(lg,">>");xf("add",ug),xf("sub",cg),xf("mul",hg),xf("div",dg),xf("modInt",pg),xf("equal",fg),xf("notEqual",mg),xf("lessThan",gg),xf("greaterThan",_g),xf("lessThanEqual",vg),xf("greaterThanEqual",yg),xf("and",xg),xf("or",bg),xf("not",Sg),xf("xor",Tg),xf("bitAnd",Mg),xf("bitNot",Eg),xf("bitOr",wg),xf("bitXor",Ag),xf("shiftLeft",Rg),xf("shiftRight",Cg);xf("remainder",((...e)=>(console.warn("TSL.OperatorNode: .remainder() has been renamed to .modInt()."),pg(...e))));class Ng extends lf{static get type(){return"MathNode"}constructor(e,t,n=null,i=null){super(),this.method=e,this.aNode=t,this.bNode=n,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(i)?0:e.getTypeLength(i);return r>s&&r>a?t:s>a?n:a>r?i:t}getNodeType(e){const t=this.method;return t===Ng.LENGTH||t===Ng.DISTANCE||t===Ng.DOT?"float":t===Ng.CROSS?"vec3":t===Ng.ALL?"bool":t===Ng.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):t===Ng.MOD?this.aNode.getNodeType(e):this.getInputType(e)}generate(e,t){let n=this.method;const i=this.getNodeType(e),r=this.getInputType(e),s=this.aNode,a=this.bNode,o=this.cNode,l=e.renderer.coordinateSystem;if(n===Ng.TRANSFORM_DIRECTION){let n=s,i=a;e.isMatrix(n.getNodeType(e))?i=fm(cm(i),0):n=fm(cm(n),0);const r=hg(n,i).xyz;return Wg(r).build(e,t)}if(n===Ng.NEGATE)return e.format("( - "+s.build(e,r)+" )",i,t);if(n===Ng.ONE_MINUS)return cg(1,s).build(e,t);if(n===Ng.RECIPROCAL)return dg(1,s).build(e,t);if(n===Ng.DIFFERENCE)return Jg(cg(s,a)).build(e,t);{const u=[];return n===Ng.CROSS||n===Ng.MOD?u.push(s.build(e,i),a.build(e,i)):l===bt&&n===Ng.STEP?u.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":r),a.build(e,r)):l===bt&&(n===Ng.MIN||n===Ng.MAX)||n===Ng.MOD?u.push(s.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):n===Ng.REFRACT?u.push(s.build(e,r),a.build(e,r),o.build(e,"float")):n===Ng.MIX?u.push(s.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(l===St&&n===Ng.ATAN&&null!==a&&(n="atan2"),u.push(s.build(e,r)),null!==a&&u.push(a.build(e,r)),null!==o&&u.push(o.build(e,r))),e.format(`${e.getMethod(n,i)}( ${u.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Ng.ALL="all",Ng.ANY="any",Ng.RADIANS="radians",Ng.DEGREES="degrees",Ng.EXP="exp",Ng.EXP2="exp2",Ng.LOG="log",Ng.LOG2="log2",Ng.SQRT="sqrt",Ng.INVERSE_SQRT="inversesqrt",Ng.FLOOR="floor",Ng.CEIL="ceil",Ng.NORMALIZE="normalize",Ng.FRACT="fract",Ng.SIN="sin",Ng.COS="cos",Ng.TAN="tan",Ng.ASIN="asin",Ng.ACOS="acos",Ng.ATAN="atan",Ng.ABS="abs",Ng.SIGN="sign",Ng.LENGTH="length",Ng.NEGATE="negate",Ng.ONE_MINUS="oneMinus",Ng.DFDX="dFdx",Ng.DFDY="dFdy",Ng.ROUND="round",Ng.RECIPROCAL="reciprocal",Ng.TRUNC="trunc",Ng.FWIDTH="fwidth",Ng.TRANSPOSE="transpose",Ng.BITCAST="bitcast",Ng.EQUALS="equals",Ng.MIN="min",Ng.MAX="max",Ng.MOD="mod",Ng.STEP="step",Ng.REFLECT="reflect",Ng.DISTANCE="distance",Ng.DIFFERENCE="difference",Ng.DOT="dot",Ng.CROSS="cross",Ng.POW="pow",Ng.TRANSFORM_DIRECTION="transformDirection",Ng.MIX="mix",Ng.CLAMP="clamp",Ng.REFRACT="refract",Ng.SMOOTHSTEP="smoothstep",Ng.FACEFORWARD="faceforward";const Pg=nm(1e-6),Dg=nm(Math.PI),Ug=Yf(Ng,Ng.ALL),Lg=Yf(Ng,Ng.ANY),Ig=Yf(Ng,Ng.RADIANS),Og=Yf(Ng,Ng.DEGREES),Fg=Yf(Ng,Ng.EXP),Bg=Yf(Ng,Ng.EXP2),kg=Yf(Ng,Ng.LOG),zg=Yf(Ng,Ng.LOG2),Gg=Yf(Ng,Ng.SQRT),Vg=Yf(Ng,Ng.INVERSE_SQRT),Hg=Yf(Ng,Ng.FLOOR),jg=Yf(Ng,Ng.CEIL),Wg=Yf(Ng,Ng.NORMALIZE),Xg=Yf(Ng,Ng.FRACT),qg=Yf(Ng,Ng.SIN),$g=Yf(Ng,Ng.COS),Yg=Yf(Ng,Ng.TAN),Kg=Yf(Ng,Ng.ASIN),Zg=Yf(Ng,Ng.ACOS),Qg=Yf(Ng,Ng.ATAN),Jg=Yf(Ng,Ng.ABS),e_=Yf(Ng,Ng.SIGN),t_=Yf(Ng,Ng.LENGTH),n_=Yf(Ng,Ng.NEGATE),i_=Yf(Ng,Ng.ONE_MINUS),r_=Yf(Ng,Ng.DFDX),s_=Yf(Ng,Ng.DFDY),a_=Yf(Ng,Ng.ROUND),o_=Yf(Ng,Ng.RECIPROCAL),l_=Yf(Ng,Ng.TRUNC),u_=Yf(Ng,Ng.FWIDTH),c_=Yf(Ng,Ng.TRANSPOSE);Ng.BITCAST;const h_=Yf(Ng,Ng.EQUALS),d_=Yf(Ng,Ng.MIN),p_=Yf(Ng,Ng.MAX),f_=Yf(Ng,Ng.MOD),m_=Yf(Ng,Ng.STEP),g_=Yf(Ng,Ng.REFLECT),__=Yf(Ng,Ng.DISTANCE),v_=Yf(Ng,Ng.DIFFERENCE),y_=Yf(Ng,Ng.DOT),x_=Yf(Ng,Ng.CROSS),b_=Yf(Ng,Ng.POW),S_=Yf(Ng,Ng.POW,2),T_=Yf(Ng,Ng.POW,3),M_=Yf(Ng,Ng.POW,4),E_=Yf(Ng,Ng.TRANSFORM_DIRECTION),w_=e=>y_(e,e),A_=Yf(Ng,Ng.MIX),R_=(e,t=0,n=1)=>Xf(new Ng(Ng.CLAMP,Xf(e),Xf(t),Xf(n))),C_=Yf(Ng,Ng.REFRACT),N_=Yf(Ng,Ng.SMOOTHSTEP),P_=Yf(Ng,Ng.FACEFORWARD),D_=Zf((([e])=>{const t=y_(e.xy,am(12.9898,78.233)),n=f_(t,Dg);return Xg(qg(n).mul(43758.5453))}));xf("all",Ug),xf("any",Lg),xf("equals",h_),xf("radians",Ig),xf("degrees",Og),xf("exp",Fg),xf("exp2",Bg),xf("log",kg),xf("log2",zg),xf("sqrt",Gg),xf("inverseSqrt",Vg),xf("floor",Hg),xf("ceil",jg),xf("normalize",Wg),xf("fract",Xg),xf("sin",qg),xf("cos",$g),xf("tan",Yg),xf("asin",Kg),xf("acos",Zg),xf("atan",Qg),xf("abs",Jg),xf("sign",e_),xf("length",t_),xf("lengthSq",w_),xf("negate",n_),xf("oneMinus",i_),xf("dFdx",r_),xf("dFdy",s_),xf("round",a_),xf("reciprocal",o_),xf("trunc",l_),xf("fwidth",u_),xf("atan2",((e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),Qg(e,t)))),xf("min",d_),xf("max",p_),xf("mod",f_),xf("step",m_),xf("reflect",g_),xf("distance",__),xf("dot",y_),xf("cross",x_),xf("pow",b_),xf("pow2",S_),xf("pow3",T_),xf("pow4",M_),xf("transformDirection",E_),xf("mix",((e,t,n)=>A_(t,n,e))),xf("clamp",R_),xf("refract",C_),xf("smoothstep",((e,t,n)=>N_(t,n,e))),xf("faceForward",P_),xf("difference",v_),xf("saturate",(e=>R_(e))),xf("cbrt",(e=>hg(e_(e),b_(Jg(e),1/3)))),xf("transpose",c_),xf("rand",D_);class U_ extends sf{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}getNodeType(e){const{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(void 0===t)return this.setup(e),this.getNodeType(e);const i=t.getNodeType(e);if(null!==n){const t=n.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(i))return t}return i}setup(e){const t=this.condNode.cache(),n=this.ifNode.cache(),i=this.elseNode?this.elseNode.cache():null,r=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const s=e.getNodeProperties(this);s.condNode=t,s.ifNode=n.context({nodeBlock:n}),s.elseNode=i?i.context({nodeBlock:i}):null}generate(e,t){const n=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:s,elseNode:a}=e.getNodeProperties(this),o="void"!==t,l=o?Pm(n).build(e):"";i.nodeProperty=l;const u=r.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let c=s.build(e,n);if(c&&(c=o?l+" = "+c+";":"return "+c+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,n);t&&(t=o?l+" = "+t+";":"return "+t+";"),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,n,t)}}const L_=Yf(U_);xf("select",L_);xf("cond",((...e)=>(console.warn("TSL.ConditionalNode: cond() has been renamed to select()."),L_(...e))));class I_ extends sf{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){this.node.build(e)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value});const n=this.node.build(e);return e.setContext(t),n}generate(e,t){const n=e.getContext();e.setContext({...e.context,...this.value});const i=this.node.build(e,t);return e.setContext(n),i}}const O_=Yf(I_);xf("context",O_),xf("label",((e,t)=>O_(e,{label:t})));class F_ extends sf{static get type(){return"VarNode"}constructor(e,t=null,n=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=n}getHash(e){return this.name||super.getHash(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:n,readOnly:i}=this,{renderer:r}=e,s=!0===r.backend.isWebGPUBackend;let a=!1,o=!1;i&&(a=e.isDeterministic(t),o=s?i:a);const l=e.getVectorType(this.getNodeType(e)),u=t.build(e,l),c=e.getVarFromNode(this,n,l,void 0,o),h=e.getPropertyName(c);let d=h;if(o)if(s)d=a?`const ${h}`:`let ${h}`;else{const n=e.getArrayCount(t);d=`const ${e.getVar(c.type,h,n)}`}return e.addLineFlowCode(`${d} = ${u}`,this),h}}const B_=Yf(F_);xf("toVar",((e,t=null)=>B_(e,t).append())),xf("toConst",((e,t=null)=>B_(e,t,!0).append()));xf("temp",(e=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),B_(e))));class k_ extends sf{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0}isGlobal(){return!0}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let n=t.varying;if(void 0===n){const i=this.name,r=this.getNodeType(e);t.varying=n=e.getVaryingFromNode(this,i,r),t.node=this.node}return n.needsInterpolation||(n.needsInterpolation="fragment"===e.shaderStage),n}setup(e){this.setupVarying(e)}analyze(e){return this.setupVarying(e),this.node.analyze(e)}generate(e){const t=e.getNodeProperties(this),n=this.setupVarying(e),i="fragment"===e.shaderStage&&!0===t.reassignPosition&&e.context.needsPositionReassign;if(void 0===t.propertyName||i){const r=this.getNodeType(e),s=e.getPropertyName(n,Xp);e.flowNodeFromShaderStage(Xp,this.node,r,s),t.propertyName=s,i?t.reassignPosition=!1:void 0===t.reassignPosition&&e.context.isPositionNodeInput&&(t.reassignPosition=!0)}return e.getPropertyName(n)}}const z_=Yf(k_);xf("toVarying",z_),xf("toVertexStage",(e=>z_(e))),xf("varying",((...e)=>(console.warn("TSL.VaryingNode: .varying() has been renamed to .toVarying()."),z_(...e)))),xf("vertexStage",((...e)=>(console.warn("TSL.VaryingNode: .vertexStage() has been renamed to .toVertexStage()."),z_(...e))));const G_=Zf((([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),n=e.mul(.0773993808),i=e.lessThanEqual(.04045);return A_(t,n,i)})).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),V_=Zf((([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),n=e.mul(12.92),i=e.lessThanEqual(.0031308);return A_(t,n,i)})).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),H_="WorkingColorSpace",j_="OutputColorSpace";class W_ extends lf{static get type(){return"ColorSpaceNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.source=t,this.target=n}resolveColorSpace(e,t){return t===H_?Xt.workingColorSpace:t===j_?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let r=t;return!1!==Xt.enabled&&n!==i&&n&&i?(Xt.getTransfer(n)===lt&&(r=fm(G_(r.rgb),r.a)),Xt.getPrimaries(n)!==Xt.getPrimaries(i)&&(r=fm(ym(Xt._getMatrix(new Ot,n,i)).mul(r.rgb),r.a)),Xt.getTransfer(i)===lt&&(r=fm(V_(r.rgb),r.a)),r):r}}const X_=(e,t)=>Xf(new W_(Xf(e),t,H_));xf("toOutputColorSpace",(e=>Xf(new W_(Xf(e),H_,j_)))),xf("toWorkingColorSpace",(e=>Xf(new W_(Xf(e),j_,H_)))),xf("workingToColorSpace",((e,t)=>Xf(new W_(Xf(e),H_,t)))),xf("colorSpaceToWorking",X_);let q_=class extends af{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,n,i)}};class $_ extends sf{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=Kp}setGroup(e){return this.group=e,this}element(e){return Xf(new q_(this,Xf(e)))}setNodeType(e){const t=Cm(null,e).getSelf();null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;eXf(new Y_(e,t,n));class Z_ extends lf{static get type(){return"ToneMappingNode"}constructor(e,t=Q_,n=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return Bp(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,n=this.toneMapping;if(0===n)return t;let i=null;const r=e.renderer.library.getToneMappingFunction(n);return null!==r?i=fm(r(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",n),i=t),i}}const Q_=K_("toneMappingExposure","float");xf("toneMapping",((e,t,n)=>((e,t,n)=>Xf(new Z_(e,Xf(t),Xf(n))))(t,n,e)));class J_ extends ff{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=i,this.usage=vt,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),n=this.value,i=e.getTypeLength(t),r=this.bufferStride||i,s=this.bufferOffset,a=!0===n.isInterleavedBuffer?n:new Lr(n,r),o=new Or(a,i,s);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(n);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=z_(this).build(e,t)}return r}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}const ev=(e,t=null,n=0,i=0)=>Xf(new J_(e,t,n,i)),tv=(e,t=null,n=0,i=0)=>ev(e,t,n,i).setInstanced(!0),nv=(e,t=null,n=0,i=0)=>((e,t=null,n=0,i=0)=>ev(e,t,n,i).setUsage(yt))(e,t,n,i).setInstanced(!0);xf("toAttribute",(e=>ev(e.value)));class iv extends sf{static get type(){return"ComputeNode"}constructor(e,t,n=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=n,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=Kp,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let n=t[0];for(let e=1;eXf(new iv(Xf(e),t,n))));class rv extends sf{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){const t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const n=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(n),r}}const sv=(e,t)=>Xf(new rv(Xf(e),t));xf("cache",sv);class av extends sf{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}xf("bypass",Yf(av));class ov extends sf{static get type(){return"RemapNode"}constructor(e,t,n,i=nm(0),r=nm(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=n,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:n,outLowNode:i,outHighNode:r,doClamp:s}=this;let a=e.sub(t).div(n.sub(t));return!0===s&&(a=a.clamp()),a.mul(r.sub(i)).add(i)}}const lv=Yf(ov,null,null,{doClamp:!1}),uv=Yf(ov);xf("remap",lv),xf("remapClamp",uv);class cv extends sf{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),i=this.snippet;if("void"!==n)return e.format(`( ${i} )`,n,t);e.addLineFlowCode(i,this)}}const hv=Yf(cv);xf("discard",(e=>(e?L_(e,hv("discard")):hv("discard")).append()));class dv extends lf{static get type(){return"RenderOutputNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const n=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||rt;return 0!==n&&(t=t.toneMapping(n)),i!==rt&&i!==Xt.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}xf("renderOutput",((e,t=null,n=null)=>Xf(new dv(Xf(e),t,n))));class pv extends sf{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const i=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),n=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),s=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(s.name,r,n);return z_(this).build(e,n)}return console.warn(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(n)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const fv=(e,t)=>Xf(new pv(e,t)),mv=(e=0)=>fv("uv"+(e>0?e:""),"vec2");class gv extends sf{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const n=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${i} )`,this.getNodeType(e),t)}}const _v=Yf(gv);class vv extends Rm{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=$p}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&void 0!==n.width){const{width:e,height:t}=n;this.value=Math.log2(Math.max(e,t))}}}const yv=Yf(vv);class xv extends Rm{static get type(){return"TextureNode"}constructor(e,t=null,n=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=qp,this.referenceNode=null,this._value=e,this._matrixUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===oe?"uvec4":this.value.type===ae?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return mv(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Cm(this.value.matrix)),this._matrixUniform.mul(cm(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Yp:qp,this}setupUV(e,t){const n=this.value;return e.isFlipY()&&(n.image instanceof ImageBitmap&&!0===n.flipY||!0===n.isRenderTargetTexture||!0===n.isFramebufferTexture||!0===n.isDepthTexture)&&(t=this.sampler?t.flipY():t.setY(im(_v(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const n=this.value;if(!n||!0!==n.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let i=this.uvNode;null!==i&&!0!==e.context.forceUVContext||!e.context.getUV||(i=e.context.getUV(this)),i||(i=this.getDefaultUV()),!0===this.updateMatrix&&(i=this.getTransformedUV(i)),i=this.setupUV(e,i);let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,n,i,r,s,a,o){const l=this.value;let u;return u=i?e.generateTextureLevel(l,t,n,i,s):r?e.generateTextureBias(l,t,n,r,s):o?e.generateTextureGrad(l,t,n,o,s):a?e.generateTextureCompare(l,t,n,a,s):!1===this.sampler?e.generateTextureLoad(l,t,n,s):e.generateTexture(l,t,n,s),u}generate(e,t){const n=this.value,i=e.getNodeProperties(this),r=super.generate(e,"property");if("sampler"===t)return r+"_sampler";if(e.isReference(t))return r;{const s=e.getDataFromNode(this);let a=s.propertyName;if(void 0===a){const{uvNode:t,levelNode:n,biasNode:o,compareNode:l,depthNode:u,gradNode:c}=i,h=this.generateUV(e,t),d=n?n.build(e,"float"):null,p=o?o.build(e,"float"):null,f=u?u.build(e,"int"):null,m=l?l.build(e,"float"):null,g=c?[c[0].build(e,"vec2"),c[1].build(e,"vec2")]:null,_=e.getVarFromNode(this);a=e.getPropertyName(_);const v=this.generateSnippet(e,r,h,d,p,f,m,g);e.addLineFlowCode(`${a} = ${v}`,this),s.snippet=v,s.propertyName=a}let o=a;const l=this.getNodeType(e);return e.needsToWorkingColorSpace(n)&&(o=X_(hv(o,l),n.colorSpace).setup(e).build(e,l)),e.format(o,l,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=Xf(e),t.referenceNode=this.getSelf(),Xf(t)}blur(e){const t=this.clone();return t.biasNode=Xf(e).mul(yv(t)),t.referenceNode=this.getSelf(),Xf(t)}level(e){const t=this.clone();return t.levelNode=Xf(e),t.referenceNode=this.getSelf(),Xf(t)}size(e){return _v(this,e)}bias(e){const t=this.clone();return t.biasNode=Xf(e),t.referenceNode=this.getSelf(),Xf(t)}compare(e){const t=this.clone();return t.compareNode=Xf(e),t.referenceNode=this.getSelf(),Xf(t)}grad(e,t){const n=this.clone();return n.gradNode=[Xf(e),Xf(t)],n.referenceNode=this.getSelf(),Xf(n)}depth(e){const t=this.clone();return t.depthNode=Xf(e),t.referenceNode=this.getSelf(),Xf(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix()}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e}}const bv=Yf(xv),Sv=(...e)=>bv(...e).setSampler(!1);class Tv extends Rm{static get type(){return"BufferNode"}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Mv=(e,t,n)=>Xf(new Tv(e,t,n));class Ev extends af{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),n=this.getNodeType(),i=this.node.getPaddedType();return e.format(t,i,n)}}class wv extends Tv{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Hp(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Yp,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,n=this.elementType;if("float"===n||"int"===n||"uint"===n)for(let n=0;nXf(new wv(e,t)),Rv=Cm(0,"uint").setGroup(Mm("cameraIndex")).toVarying("v_cameraIndex"),Cv=Cm("float").label("cameraNear").setGroup(wm).onRenderUpdate((({camera:e})=>e.near)),Nv=Cm("float").label("cameraFar").setGroup(wm).onRenderUpdate((({camera:e})=>e.far)),Pv=Zf((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.projectionMatrix);t=Av(n).setGroup(wm).label("cameraProjectionMatrices").element(Rv).toVar("cameraProjectionMatrix")}else t=Cm("mat4").label("cameraProjectionMatrix").setGroup(wm).onRenderUpdate((({camera:e})=>e.projectionMatrix));return t})).once()(),Dv=Zf((({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.matrixWorldInverse);t=Av(n).setGroup(wm).label("cameraViewMatrices").element(Rv).toVar("cameraViewMatrix")}else t=Cm("mat4").label("cameraViewMatrix").setGroup(wm).onRenderUpdate((({camera:e})=>e.matrixWorldInverse));return t})).once()(),Uv=Cm(new un).label("cameraPosition").setGroup(wm).onRenderUpdate((({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),Lv=new Nn;class Iv extends sf{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Kp,this._uniformNode=new Rm(null)}getNodeType(){const e=this.scope;return e===Iv.WORLD_MATRIX?"mat4":e===Iv.POSITION||e===Iv.VIEW_POSITION||e===Iv.DIRECTION||e===Iv.SCALE?"vec3":e===Iv.RADIUS?"float":void 0}update(e){const t=this.object3d,n=this._uniformNode,i=this.scope;if(i===Iv.WORLD_MATRIX)n.value=t.matrixWorld;else if(i===Iv.POSITION)n.value=n.value||new un,n.value.setFromMatrixPosition(t.matrixWorld);else if(i===Iv.SCALE)n.value=n.value||new un,n.value.setFromMatrixScale(t.matrixWorld);else if(i===Iv.DIRECTION)n.value=n.value||new un,t.getWorldDirection(n.value);else if(i===Iv.VIEW_POSITION){const i=e.camera;n.value=n.value||new un,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Iv.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),Lv.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),n.value=Lv.radius}}generate(e){const t=this.scope;return t===Iv.WORLD_MATRIX?this._uniformNode.nodeType="mat4":t===Iv.POSITION||t===Iv.VIEW_POSITION||t===Iv.DIRECTION||t===Iv.SCALE?this._uniformNode.nodeType="vec3":t===Iv.RADIUS&&(this._uniformNode.nodeType="float"),this._uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}Iv.WORLD_MATRIX="worldMatrix",Iv.POSITION="position",Iv.SCALE="scale",Iv.VIEW_POSITION="viewPosition",Iv.DIRECTION="direction",Iv.RADIUS="radius",Iv.DIRECTION,Iv.WORLD_MATRIX;const Ov=Yf(Iv,Iv.POSITION);Iv.SCALE,Iv.VIEW_POSITION,Iv.RADIUS;class Fv extends Iv{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Bv=Kf(Fv,Fv.WORLD_MATRIX),kv=Cm(new Ot).onObjectUpdate((({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld))),zv=Zf((e=>e.renderer.nodes.modelViewMatrix||Gv)).once()().toVar("modelViewMatrix"),Gv=Dv.mul(Bv),Vv=fv("position","vec3"),Hv=Vv.toVarying("positionLocal"),jv=Vv.toVarying("positionPrevious"),Wv=Bv.mul(Hv).xyz.toVarying("v_positionWorld").context({needsPositionReassign:!0}),Xv=Hv.transformDirection(Bv).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection").context({needsPositionReassign:!0}),qv=Zf((e=>e.context.setupPositionView()),"vec3").once()().toVarying("v_positionView").context({needsPositionReassign:!0}),$v=qv.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class Yv extends sf{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){const{renderer:t,material:n}=e;return t.coordinateSystem===bt&&1===n.side?"false":e.getFrontFacing()}}const Kv=nm(Kf(Yv)).mul(2).sub(1),Zv=fv("normal","vec3"),Qv=Zf((e=>!1===e.geometry.hasAttribute("normal")?(console.warn('TSL.NormalNode: Vertex attribute "normal" not found on geometry.'),cm(0,1,0)):Zv),"vec3").once()().toVar("normalLocal"),Jv=qv.dFdx().cross(qv.dFdy()).normalize().toVar("normalFlat"),ey=Zf((e=>{let t;return t=!0===e.material.flatShading?Jv:z_(ay(Qv),"v_normalView").normalize(),t}),"vec3").once()().toVar("normalView"),ty=z_(ey.transformDirection(Dv),"v_normalWorld").normalize().toVar("normalWorld"),ny=Zf((e=>e.context.setupNormal().context({getUV:null})),"vec3").once()().mul(Kv).toVar("transformedNormalView"),iy=ny.transformDirection(Dv).toVar("transformedNormalWorld"),ry=Zf((e=>e.context.setupClearcoatNormal().context({getUV:null})),"vec3").once()().mul(Kv).toVar("transformedClearcoatNormalView"),sy=Zf((([e,t=Bv])=>{const n=ym(t),i=e.div(cm(n[0].dot(n[0]),n[1].dot(n[1]),n[2].dot(n[2])));return n.mul(i).xyz})),ay=Zf((([e],t)=>{const n=t.renderer.nodes.modelNormalViewMatrix;if(null!==n)return n.transformDirection(e);const i=kv.mul(e);return Dv.transformDirection(i)})),oy=new Yn,ly=new kn,uy=Cm(0).onReference((({material:e})=>e)).onObjectUpdate((({material:e})=>e.refractionRatio)),cy=Cm(1).onReference((({material:e})=>e)).onObjectUpdate((function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity})),hy=Cm(new kn).onReference((function(e){return e.material})).onObjectUpdate((function({material:e,scene:t}){const n=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return n?(oy.copy(n),ly.makeRotationFromEuler(oy)):ly.identity(),ly})),dy=$v.negate().reflect(ny),py=$v.negate().refract(ny,uy),fy=dy.transformDirection(Dv).toVar("reflectVector"),my=py.transformDirection(Dv).toVar("reflectVector");class gy extends xv{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,i=null){super(e,t,n,i),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===V?fy:e.mapping===H?my:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),cm(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return e.renderer.coordinateSystem!==St&&n.isRenderTargetTexture||(t=cm(t.x.negate(),t.yz)),hy.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const _y=Yf(gy);class vy extends af{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,n,i)}}class yy extends sf{static get type(){return"ReferenceNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=Kp}element(e){return Xf(new vy(this,Xf(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?Mv(null,e,this.count):Array.isArray(this.getValueFromReference())?Av(null,e):"texture"===e?bv(null):"cubeTexture"===e?_y(null):Cm(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;eXf(new yy(e,t,n)),by=(e,t,n,i)=>Xf(new yy(e,t,i,n));class Sy extends yy{static get type(){return"MaterialReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.material=n,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Ty=(e,t,n=null)=>Xf(new Sy(e,t,n)),My=Zf((e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),fv("tangent","vec4"))))(),Ey=My.xyz.toVar("tangentLocal"),wy=zv.mul(fm(Ey,0)).xyz.toVarying("v_tangentView").normalize().toVar("tangentView");var Ay;const Ry=ym(wy,z_((Ay=ey.cross(wy),Ay.mul(My.w).xyz),"v_bitangentView").normalize().toVar("bitangentView"),ey),Cy=(()=>{let e=qm.cross($v);return e=e.cross(qm).normalize(),e=A_(e,ny,Wm.mul(Im.oneMinus()).oneMinus().pow2().pow2()).normalize(),e})(),Ny=Zf((e=>{const{eye_pos:t,surf_norm:n,mapN:i,uv:r}=e,s=t.dFdx(),a=t.dFdy(),o=r.dFdx(),l=r.dFdy(),u=n,c=a.cross(u),h=u.cross(s),d=c.mul(o.x).add(h.mul(l.x)),p=c.mul(o.y).add(h.mul(l.y)),f=d.dot(d).max(p.dot(p)),m=Kv.mul(f.inverseSqrt());return ug(d.mul(i.x,m),p.mul(i.y,m),u.mul(i.z)).normalize()}));class Py extends lf{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup(e){const{normalMapType:t,scaleNode:n}=this;let i=this.node.mul(2).sub(1);null!==n&&(i=cm(i.xy.mul(n),i.z));let r=null;if(1===t)r=ay(i);else if(0===t){r=!0===e.hasGeometryAttribute("tangent")?Ry.mul(i).normalize():Ny({eye_pos:qv,surf_norm:ey,mapN:i,uv:mv()})}return r}}const Dy=Yf(Py),Uy=Zf((({textureNode:e,bumpScale:t})=>{const n=t=>e.cache().context({getUV:e=>t(e.uvNode||mv()),forceUVContext:!0}),i=nm(n((e=>e)));return am(nm(n((e=>e.add(e.dFdx())))).sub(i),nm(n((e=>e.add(e.dFdy())))).sub(i)).mul(t)})),Ly=Zf((e=>{const{surf_pos:t,surf_norm:n,dHdxy:i}=e,r=t.dFdx().normalize(),s=n,a=t.dFdy().normalize().cross(s),o=s.cross(r),l=r.dot(a).mul(Kv),u=l.sign().mul(i.x.mul(a).add(i.y.mul(o)));return l.abs().mul(n).sub(u).normalize()}));class Iy extends lf{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=Uy({textureNode:this.textureNode,bumpScale:e});return Ly({surf_pos:qv,surf_norm:ey,dHdxy:t})}}const Oy=Yf(Iy),Fy=new Map;class By extends sf{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=Fy.get(e);return void 0===n&&(n=Ty(e,t),Fy.set(e,n)),n}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,n=this.scope;let i=null;if(n===By.COLOR){const e=void 0!==t.color?this.getColor(n):cm();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(n===By.OPACITY){const e=this.getFloat(n);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(n===By.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:nm(1);else if(n===By.SPECULAR_INTENSITY){const e=this.getFloat(n);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(n).a):e}else if(n===By.SPECULAR_COLOR){const e=this.getColor(n);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(n).rgb):e}else if(n===By.ROUGHNESS){const e=this.getFloat(n);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(n).g):e}else if(n===By.METALNESS){const e=this.getFloat(n);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(n).b):e}else if(n===By.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(n).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(n)):r}else if(n===By.NORMAL)t.normalMap?(i=Dy(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType):i=t.bumpMap?Oy(this.getTexture("bump").r,this.getFloat("bumpScale")):ey;else if(n===By.CLEARCOAT){const e=this.getFloat(n);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===By.CLEARCOAT_ROUGHNESS){const e=this.getFloat(n);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===By.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?Dy(this.getTexture(n),this.getCache(n+"Scale","vec2")):ey;else if(n===By.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(n===By.SHEEN_ROUGHNESS){const e=this.getFloat(n);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(n).a):e,i=i.clamp(.07,1)}else if(n===By.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(n);i=vm(bx.x,bx.y,bx.y.negate(),bx.x).mul(e.rg.mul(2).sub(am(1)).normalize().mul(e.b))}else i=bx;else if(n===By.IRIDESCENCE_THICKNESS){const e=xy("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=xy("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(n).g).add(r)}else i=e}else if(n===By.TRANSMISSION){const e=this.getFloat(n);i=t.transmissionMap?e.mul(this.getTexture(n).r):e}else if(n===By.THICKNESS){const e=this.getFloat(n);i=t.thicknessMap?e.mul(this.getTexture(n).g):e}else if(n===By.IOR)i=this.getFloat(n);else if(n===By.LIGHT_MAP)i=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity"));else if(n===By.AO)i=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else{const t=this.getNodeType(e);i=this.getCache(n,t)}return i}}By.ALPHA_TEST="alphaTest",By.COLOR="color",By.OPACITY="opacity",By.SHININESS="shininess",By.SPECULAR="specular",By.SPECULAR_STRENGTH="specularStrength",By.SPECULAR_INTENSITY="specularIntensity",By.SPECULAR_COLOR="specularColor",By.REFLECTIVITY="reflectivity",By.ROUGHNESS="roughness",By.METALNESS="metalness",By.NORMAL="normal",By.CLEARCOAT="clearcoat",By.CLEARCOAT_ROUGHNESS="clearcoatRoughness",By.CLEARCOAT_NORMAL="clearcoatNormal",By.EMISSIVE="emissive",By.ROTATION="rotation",By.SHEEN="sheen",By.SHEEN_ROUGHNESS="sheenRoughness",By.ANISOTROPY="anisotropy",By.IRIDESCENCE="iridescence",By.IRIDESCENCE_IOR="iridescenceIOR",By.IRIDESCENCE_THICKNESS="iridescenceThickness",By.IOR="ior",By.TRANSMISSION="transmission",By.THICKNESS="thickness",By.ATTENUATION_DISTANCE="attenuationDistance",By.ATTENUATION_COLOR="attenuationColor",By.LINE_SCALE="scale",By.LINE_DASH_SIZE="dashSize",By.LINE_GAP_SIZE="gapSize",By.LINE_WIDTH="linewidth",By.LINE_DASH_OFFSET="dashOffset",By.POINT_SIZE="size",By.DISPERSION="dispersion",By.LIGHT_MAP="light",By.AO="ao";const ky=Kf(By,By.ALPHA_TEST),zy=Kf(By,By.COLOR),Gy=Kf(By,By.SHININESS),Vy=Kf(By,By.EMISSIVE),Hy=Kf(By,By.OPACITY),jy=Kf(By,By.SPECULAR),Wy=Kf(By,By.SPECULAR_INTENSITY),Xy=Kf(By,By.SPECULAR_COLOR),qy=Kf(By,By.SPECULAR_STRENGTH),$y=Kf(By,By.REFLECTIVITY),Yy=Kf(By,By.ROUGHNESS),Ky=Kf(By,By.METALNESS),Zy=Kf(By,By.NORMAL),Qy=Kf(By,By.CLEARCOAT),Jy=Kf(By,By.CLEARCOAT_ROUGHNESS),ex=Kf(By,By.CLEARCOAT_NORMAL),tx=Kf(By,By.ROTATION),nx=Kf(By,By.SHEEN),ix=Kf(By,By.SHEEN_ROUGHNESS),rx=Kf(By,By.ANISOTROPY),sx=Kf(By,By.IRIDESCENCE),ax=Kf(By,By.IRIDESCENCE_IOR),ox=Kf(By,By.IRIDESCENCE_THICKNESS),lx=Kf(By,By.TRANSMISSION),ux=Kf(By,By.THICKNESS),cx=Kf(By,By.IOR),hx=Kf(By,By.ATTENUATION_DISTANCE),dx=Kf(By,By.ATTENUATION_COLOR),px=Kf(By,By.LINE_SCALE),fx=Kf(By,By.LINE_DASH_SIZE),mx=Kf(By,By.LINE_GAP_SIZE);By.LINE_WIDTH;const gx=Kf(By,By.LINE_DASH_OFFSET),_x=Kf(By,By.POINT_SIZE),vx=Kf(By,By.DISPERSION),yx=Kf(By,By.LIGHT_MAP),xx=Kf(By,By.AO),bx=Cm(new It).onReference((function(e){return e.material})).onRenderUpdate((function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))})),Sx=Zf((e=>e.context.setupModelViewProjection()),"vec4").once()().toVarying("v_modelViewProjection");class Tx extends sf{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),n=this.scope;let i,r;if(n===Tx.VERTEX)i=e.getVertexIndex();else if(n===Tx.INSTANCE)i=e.getInstanceIndex();else if(n===Tx.DRAW)i=e.getDrawIndex();else if(n===Tx.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(n===Tx.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(n!==Tx.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+n);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=z_(this).build(e,t)}return r}}Tx.VERTEX="vertex",Tx.INSTANCE="instance",Tx.SUBGROUP="subgroup",Tx.INVOCATION_LOCAL="invocationLocal",Tx.INVOCATION_SUBGROUP="invocationSubgroup",Tx.DRAW="draw";const Mx=Kf(Tx,Tx.VERTEX),Ex=Kf(Tx,Tx.INSTANCE);Tx.SUBGROUP,Tx.INVOCATION_SUBGROUP,Tx.INVOCATION_LOCAL;const wx=Kf(Tx,Tx.DRAW);class Ax extends sf{static get type(){return"InstanceNode"}constructor(e,t,n){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=n,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=$p,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:n,instanceColor:i}=this;let{instanceMatrixNode:r,instanceColorNode:s}=this;if(null===r){if(t<=1e3)r=Mv(n.array,"mat4",Math.max(t,1)).element(Ex);else{const e=new la(n.array,16,1);this.buffer=e;const t=n.usage===yt?nv:tv,i=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];r=xm(...i)}this.instanceMatrixNode=r}if(i&&null===s){const e=new kr(i.array,3),t=i.usage===yt?nv:tv;this.bufferColor=e,s=cm(t(e,"vec3",3,0)),this.instanceColorNode=s}const a=r.mul(Hv).xyz;if(Hv.assign(a),e.hasGeometryAttribute("normal")){const e=sy(Qv,r);Qv.assign(e)}null!==this.instanceColorNode&&Dm("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==yt&&null!==this.buffer&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==yt&&null!==this.bufferColor&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}class Rx extends Ax{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:n,instanceColor:i}=e;super(t,n,i),this.instancedMesh=e}}const Cx=Yf(Rx);class Nx extends sf{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=Ex:this.batchingIdNode=wx);const t=Zf((([e])=>{const t=im(_v(Sv(this.batchMesh._indirectTexture),0)),n=im(e).modInt(t),i=im(e).div(t);return Sv(this.batchMesh._indirectTexture,om(n,i)).x})).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),n=t(im(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=_v(Sv(i),0),s=nm(n).mul(4).toInt().toVar(),a=s.modInt(r),o=s.div(im(r)),l=xm(Sv(i,om(a,o)),Sv(i,om(a.add(1),o)),Sv(i,om(a.add(2),o)),Sv(i,om(a.add(3),o))),u=this.batchMesh._colorsTexture;if(null!==u){const e=Zf((([e])=>{const t=_v(Sv(u),0).x,n=e,i=n.modInt(t),r=n.div(t);return Sv(u,om(i,r)).rgb})).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(n);Dm("vec3","vBatchColor").assign(t)}const c=ym(l);Hv.assign(l.mul(Hv));const h=Qv.div(cm(c[0].dot(c[0]),c[1].dot(c[1]),c[2].dot(c[2]))),d=c.mul(h).xyz;Qv.assign(d),e.hasGeometryAttribute("tangent")&&Ey.mulAssign(c)}}const Px=Yf(Nx),Dx=new WeakMap;class Ux extends sf{static get type(){return"SkinningNode"}constructor(e,t=!1){let n,i,r;super("void"),this.skinnedMesh=e,this.useReference=t,this.updateType=Kp,this.skinIndexNode=fv("skinIndex","uvec4"),this.skinWeightNode=fv("skinWeight","vec4"),t?(n=xy("bindMatrix","mat4"),i=xy("bindMatrixInverse","mat4"),r=by("skeleton.boneMatrices","mat4",e.skeleton.bones.length)):(n=Cm(e.bindMatrix,"mat4"),i=Cm(e.bindMatrixInverse,"mat4"),r=Mv(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length)),this.bindMatrixNode=n,this.bindMatrixInverseNode=i,this.boneMatricesNode=r,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=Hv){const{skinIndexNode:n,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:s}=this,a=e.element(n.x),o=e.element(n.y),l=e.element(n.z),u=e.element(n.w),c=r.mul(t),h=ug(a.mul(i.x).mul(c),o.mul(i.y).mul(c),l.mul(i.z).mul(c),u.mul(i.w).mul(c));return s.mul(h).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=Qv){const{skinIndexNode:n,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:s}=this,a=e.element(n.x),o=e.element(n.y),l=e.element(n.z),u=e.element(n.w);let c=ug(i.x.mul(a),i.y.mul(o),i.z.mul(l),i.w.mul(u));return c=s.mul(c).mul(r),c.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=by("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,jv)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===Wp(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&jv.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(Hv.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();Qv.assign(t),e.hasGeometryAttribute("tangent")&&Ey.assign(t)}}generate(e,t){if("void"!==t)return Hv.build(e,t)}update(e){const t=(this.useReference?e.object:this.skinnedMesh).skeleton;Dx.get(t)!==e.frameId&&(Dx.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}class Lx extends sf{static get type(){return"LoopNode"}constructor(e=[]){super(),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const n={};for(let e=0,t=this.params.length-1;eNumber(s)?">=":"<"));const c={start:r,end:s},h=c.start,d=c.end;let p="",f="",m="";u||(u="int"===o||"uint"===o?l.includes("<")?"++":"--":l.includes("<")?"+= 1.":"-= 1."),p+=e.getVar(o,a)+" = "+h,f+=a+" "+l+" "+d,m+=a+" "+u;const g=`for ( ${p}; ${f}; ${m} )`;e.addFlowCode((0===t?"\n":"")+e.tab+g+" {\n\n").addFlowTab()}const r=i.build(e,"void"),s=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,n=this.params.length-1;tXf(new Lx($f(e,"int"))).append(),Ox=new WeakMap,Fx=new nn,Bx=Zf((({bufferMap:e,influence:t,stride:n,width:i,depth:r,offset:s})=>{const a=im(Mx).mul(n).add(s),o=a.div(i),l=a.sub(o.mul(i));return Sv(e,om(l,o)).depth(r).mul(t)}));class kx extends sf{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Cm(1),this.updateType=Kp}setup(e){const{geometry:t}=e,n=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,s=void 0!==r?r.length:0,{texture:a,stride:o,size:l}=function(e){const t=void 0!==e.morphAttributes.position,n=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=void 0!==r?r.length:0;let a=Ox.get(e);if(void 0===a||a.count!==s){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let c=0;!0===t&&(c=1),!0===n&&(c=2),!0===i&&(c=3);let h=e.attributes.position.count*c,d=1;const p=4096;h>p&&(d=Math.ceil(h/p),h=p);const f=new Float32Array(h*d*4*s),m=new an(f,h,d,s);m.type=le,m.needsUpdate=!0;const g=4*c;for(let v=0;v{const t=nm(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Sv(this.mesh.morphTexture,om(im(e).add(1),im(Ex))).r):t.assign(xy("morphTargetInfluences","float").element(e).toVar()),!0===n&&Hv.addAssign(Bx({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:im(0)})),!0===i&&Qv.addAssign(Bx({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:im(1)}))}))}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce(((e,t)=>e+t),0)}}const zx=Yf(kx);class Gx extends sf{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Vx extends Gx{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Hx extends I_{static get type(){return"LightingContextNode"}constructor(e,t=null,n=null,i=null){super(e),this.lightingModel=t,this.backdropNode=n,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,n={directDiffuse:cm().toVar("directDiffuse"),directSpecular:cm().toVar("directSpecular"),indirectDiffuse:cm().toVar("indirectDiffuse"),indirectSpecular:cm().toVar("indirectSpecular")};return{radiance:cm().toVar("radiance"),irradiance:cm().toVar("irradiance"),iblIrradiance:cm().toVar("iblIrradiance"),ambientOcclusion:nm(1).toVar("ambientOcclusion"),reflectedLight:n,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const jx=Yf(Hx);class Wx extends Gx{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let Xx,qx;class $x extends sf{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===$x.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=qp;return this.scope!==$x.SIZE&&this.scope!==$x.VIEWPORT||(e=Yp),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===$x.VIEWPORT?null!==t?qx.copy(t.viewport):(e.getViewport(qx),qx.multiplyScalar(e.getPixelRatio())):null!==t?(Xx.width=t.width,Xx.height=t.height):e.getDrawingBufferSize(Xx)}setup(){const e=this.scope;let t=null;return t=e===$x.SIZE?Cm(Xx||(Xx=new It)):e===$x.VIEWPORT?Cm(qx||(qx=new nn)):am(Zx.div(Kx)),t}generate(e){if(this.scope===$x.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(Kx).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}$x.COORDINATE="coordinate",$x.VIEWPORT="viewport",$x.SIZE="size",$x.UV="uv";const Yx=Kf($x,$x.UV),Kx=Kf($x,$x.SIZE),Zx=Kf($x,$x.COORDINATE),Qx=Kf($x,$x.VIEWPORT);Qx.zw,Qx.xy;const Jx=new It;class eb extends xv{static get type(){return"ViewportTextureNode"}constructor(e=Yx,t=null,n=null){null===n&&((n=new is).minFilter=te),super(n,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=$p}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Jx);const n=this.value;n.image.width===Jx.width&&n.image.height===Jx.height||(n.image.width=Jx.width,n.image.height=Jx.height,n.needsUpdate=!0);const i=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=i}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const tb=Yf(eb,null,null,{generateMipmaps:!0});let nb=null;class ib extends eb{static get type(){return"ViewportDepthTextureNode"}constructor(e=Yx,t=null){null===nb&&(nb=new rs),super(e,t,nb)}}const rb=Yf(ib);class sb extends sf{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===sb.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let i=null;if(t===sb.DEPTH_BASE)null!==n&&(i=cb().assign(n));else if(t===sb.DEPTH)i=e.isPerspectiveCamera?ob(qv.z,Cv,Nv):ab(qv.z,Cv,Nv);else if(t===sb.LINEAR_DEPTH)if(null!==n)if(e.isPerspectiveCamera){const e=lb(n,Cv,Nv);i=ab(e,Cv,Nv)}else i=n;else i=ab(qv.z,Cv,Nv);return i}}sb.DEPTH_BASE="depthBase",sb.DEPTH="depth",sb.LINEAR_DEPTH="linearDepth";const ab=(e,t,n)=>e.add(t).div(t.sub(n)),ob=(e,t,n)=>t.add(e).mul(n).div(n.sub(t).mul(e)),lb=(e,t,n)=>t.mul(n).div(n.sub(t).mul(e).sub(n)),ub=(e,t,n)=>{t=t.max(1e-6).toVar();const i=zg(e.negate().div(t)),r=zg(n.div(t));return i.div(r)},cb=Yf(sb,sb.DEPTH_BASE),hb=Kf(sb,sb.DEPTH);sb.LINEAR_DEPTH;rb(),hb.assign=e=>cb(e);const db=Yf(class extends sf{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}});class pb extends sf{static get type(){return"ClippingNode"}constructor(e=pb.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:n,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===pb.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,i):this.scope===pb.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(n,i)}setupAlphaToCoverage(e,t){return Zf((()=>{const n=nm().toVar("distanceToPlane"),i=nm().toVar("distanceToGradient"),r=nm(1).toVar("clipOpacity"),s=t.length;if(!1===this.hardwareClipping&&s>0){const e=Av(t);Ix(s,(({i:t})=>{const s=e.element(t);n.assign(qv.dot(s.xyz).negate().add(s.w)),i.assign(n.fwidth().div(2)),r.mulAssign(N_(i.negate(),i,n))}))}const a=e.length;if(a>0){const t=Av(e),s=nm(1).toVar("intersectionClipOpacity");Ix(a,(({i:e})=>{const r=t.element(e);n.assign(qv.dot(r.xyz).negate().add(r.w)),i.assign(n.fwidth().div(2)),s.mulAssign(N_(i.negate(),i,n).oneMinus())})),r.mulAssign(s.oneMinus())}Um.a.mulAssign(r),Um.a.equal(0).discard()}))()}setupDefault(e,t){return Zf((()=>{const n=t.length;if(!1===this.hardwareClipping&&n>0){const e=Av(t);Ix(n,(({i:t})=>{const n=e.element(t);qv.dot(n.xyz).greaterThan(n.w).discard()}))}const i=e.length;if(i>0){const t=Av(e),n=sm(!0).toVar("clipped");Ix(i,(({i:e})=>{const i=t.element(e);n.assign(qv.dot(i.xyz).greaterThan(i.w).and(n))})),n.discard()}}))()}setupHardwareClipping(e,t){const n=e.length;return t.enableHardwareClipping(n),Zf((()=>{const i=Av(e),r=db(t.getClipDistance());Ix(n,(({i:e})=>{const t=i.element(e),n=qv.dot(t.xyz).sub(t.w).negate();r.element(e).assign(n)}))}))()}}pb.ALPHA_TO_COVERAGE="alphaToCoverage",pb.DEFAULT="default",pb.HARDWARE="hardware";const fb=Zf((([e])=>Xg(hg(1e4,qg(hg(17,e.x).add(hg(.1,e.y)))).mul(ug(.1,Jg(qg(hg(13,e.y).add(e.x)))))))),mb=Zf((([e])=>fb(am(fb(e.xy),e.z)))),gb=Zf((([e])=>{const t=p_(t_(r_(e.xyz)),t_(s_(e.xyz))),n=nm(1).div(nm(.05).mul(t)).toVar("pixScale"),i=am(Bg(Hg(zg(n))),Bg(jg(zg(n)))),r=am(mb(Hg(i.x.mul(e.xyz))),mb(Hg(i.y.mul(e.xyz)))),s=Xg(zg(n)),a=ug(hg(s.oneMinus(),r.x),hg(s,r.y)),o=d_(s,s.oneMinus()),l=cm(a.mul(a).div(hg(2,o).mul(cg(1,o))),a.sub(hg(.5,o)).div(cg(1,o)),cg(1,cg(1,a).mul(cg(1,a)).div(hg(2,o).mul(cg(1,o))))),u=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return R_(u,1e-6,1)})).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class _b extends Li{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.shadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null}customProgramCacheKey(){return this.type+kp(this)}build(e){this.setup(e)}setupObserver(e){return new Ip(e)}setup(e){e.context.setupNormal=()=>this.setupNormal(e),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();e.addStack();const i=this.vertexNode||this.setupVertex(e);let r;e.stack.outputNode=i,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const s=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==n?!0===n.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==s&&e.stack.add(s);const a=fm(i,Um.a).max(0);if(r=this.setupOutput(e,a),Zm.assign(r),null!==this.outputNode&&(r=this.outputNode),null!==n){const e=t.getMRT(),n=this.mrtNode;null!==e?(r=e,null!==n&&(r=e.merge(n))):null!==n&&(r=n)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=fm(t)),r=this.setupOutput(e,t)}e.stack.outputNode=r,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:n}=e.clippingContext;let i=null;if(t.length>0||n.length>0){const t=e.renderer.samples;this.alphaToCoverage&&t>1?i=Xf(new pb(pb.ALPHA_TO_COVERAGE)):e.stack.add(Xf(new pb))}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.add(Xf(new pb(pb.HARDWARE))),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:n}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=n.isPerspectiveCamera?ub(qv.z,Cv,Nv):ab(qv.z,Cv,Nv))}null!==i&&hb.assign(i).append()}setupPositionView(){return zv.mul(Hv).xyz}setupModelViewProjection(){return Pv.mul(qv)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),Sx}setupPosition(e){const{object:t,geometry:n}=e;var i;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&zx(t).append(),!0===t.isSkinnedMesh&&(i=t,Xf(new Ux(i,!0))).append(),this.displacementMap){const e=Ty("displacementMap","texture"),t=Ty("displacementScale","float"),n=Ty("displacementBias","float");Hv.addAssign(Qv.normalize().mul(e.x.mul(t).add(n)))}return t.isBatchedMesh&&Px(t).append(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&Cx(t).append(),null!==this.positionNode&&Hv.assign(this.positionNode.context({isPositionNodeInput:!0})),Hv}setupDiffuseColor({object:e,geometry:t}){let n=this.colorNode?fm(this.colorNode):zy;if(!0===this.vertexColors&&t.hasAttribute("color")&&(n=fm(n.xyz.mul(fv("color","vec3")),n.a)),e.instanceColor){n=Dm("vec3","vInstanceColor").mul(n)}if(e.isBatchedMesh&&e._colorsTexture){n=Dm("vec3","vBatchColor").mul(n)}Um.assign(n);const i=this.opacityNode?nm(this.opacityNode):Hy;if(Um.a.assign(Um.a.mul(i)),null!==this.alphaTestNode||this.alphaTest>0){const e=null!==this.alphaTestNode?nm(this.alphaTestNode):ky;Um.a.lessThanEqual(e).discard()}!0===this.alphaHash&&Um.a.lessThan(gb(Hv)).discard(),!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage&&Um.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?cm(0):Um.rgb}setupNormal(){return this.normalNode?cm(this.normalNode):Zy}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Ty("envMap","cubeTexture"):Ty("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Wx(yx)),t}setupLights(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:xx;t.push(new Vx(e))}let r=this.lightsNode||e.lightsNode;return t.length>0&&(r=e.renderer.lighting.createNode([...r.getLights(),...t])),r}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:i,emissiveNode:r}=this,s=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(s&&s.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=jx(s,t,n,i)}else null!==n&&(a=cm(null!==i?A_(a,n,i):n));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(Lm.assign(cm(r||Vy)),a=a.add(Lm)),a}setupFog(e,t){const n=e.fogNode;return n&&(Zm.assign(t),t=fm(n)),t}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),t}setDefaultValues(e){for(const t in e){const n=e[t];void 0===this[t]&&(this[t]=n,n&&n.clone&&(this[t]=n.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const n=Li.prototype.toJSON.call(this,e),i=zp(this);n.inputNodes={};for(const{property:t,childNode:r}of i)n.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const n in e){const i=e[n];delete i.metadata,t.push(i)}return t}if(t){const t=r(e.textures),i=r(e.images),s=r(e.nodes);t.length>0&&(n.textures=t),i.length>0&&(n.images=i),s.length>0&&(n.nodes=s)}return n}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.shadowPositionNode=e.shadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const vb=new qr;class yb extends _b{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(vb),this.setValues(e)}}const xb=new Us;class bb extends _b{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(xb),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?nm(this.offsetNode):gx,t=this.dashScaleNode?nm(this.dashScaleNode):px,n=this.dashSizeNode?nm(this.dashSizeNode):fx,i=this.gapSizeNode?nm(this.gapSizeNode):mx;Qm.assign(n),Jm.assign(i);const r=z_(fv("lineDistance").mul(t));(e?r.add(e):r).mod(Qm.add(Jm)).greaterThan(Qm).discard()}}const Sb=new Rs;class Tb extends _b{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Sb),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?nm(this.opacityNode):Hy;Um.assign(X_(fm(Xf(ny).mul(.5).add(.5),e),st))}}class Mb extends lf{static get type(){return"EquirectUVNode"}constructor(e=Xv){super("vec2"),this.dirNode=e}setup(){const e=this.dirNode,t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),n=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return am(t,n)}}const Eb=Yf(Mb);class wb extends Cr{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r=new mr(5,5,5),s=Eb(Xv),a=new _b;a.colorNode=bv(t,s,0),a.side=1,a.blending=0;const o=new pr(r,a),l=new Ur;l.add(o),t.minFilter===te&&(t.minFilter=J);const u=new Ar(1,10,this),c=e.getMRT();return e.setMRT(null),u.update(e,l),e.setMRT(c),t.minFilter=n,t.currentGenerateMipmaps=i,o.geometry.dispose(),o.material.dispose(),this}}const Ab=new WeakMap;class Rb extends lf{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=_y();const t=new Rr;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Yp}updateBefore(e){const{renderer:t,material:n}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:n[i.property];if(e&&e.isTexture){const n=e.mapping;if(n===j||n===W){if(Ab.has(e)){const t=Ab.get(e);Nb(t,e.mapping),this._cubeTexture=t}else{const n=e.image;if(function(e){return null!=e&&e.height>0}(n)){const i=new wb(n.height);i.fromEquirectangularTexture(t,e),Nb(i.texture,e.mapping),this._cubeTexture=i.texture,Ab.set(e,i.texture),e.addEventListener("dispose",Cb)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Cb(e){const t=e.target;t.removeEventListener("dispose",Cb);const n=Ab.get(t);void 0!==n&&(Ab.delete(t),n.dispose())}function Nb(e,t){t===j?e.mapping=V:t===W&&(e.mapping=H)}const Pb=Yf(Rb);class Db extends Gx{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Pb(this.envNode)}}class Ub extends Gx{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=nm(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Lb{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Ib extends Lb{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,i=e.irradianceLightMap;n.indirectDiffuse.assign(fm(0)),i?n.indirectDiffuse.addAssign(i):n.indirectDiffuse.addAssign(fm(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(Um.rgb)}finish(e){const{material:t,context:n}=e,i=n.outgoingLight,r=e.context.environment;if(r)switch(t.combine){case 0:i.rgb.assign(A_(i.rgb,i.rgb.mul(r.rgb),qy.mul($y)));break;case 1:i.rgb.assign(A_(i.rgb,r.rgb,qy.mul($y)));break;case 2:i.rgb.addAssign(r.rgb.mul(qy.mul($y)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine)}}}const Ob=new Ii;class Fb extends _b{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Ob),this.setValues(e)}setupNormal(){return ey}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Db(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Ub(yx)),t}setupOutgoingLight(){return Um.rgb}setupLightingModel(){return new Ib}}const Bb=Zf((({f0:e,f90:t,dotVH:n})=>{const i=n.mul(-5.55473).sub(6.98316).mul(n).exp2();return e.mul(i.oneMinus()).add(t.mul(i))})),kb=Zf((e=>e.diffuseColor.mul(1/Math.PI))),zb=Zf((({dotNH:e})=>Km.mul(nm(.5)).add(1).mul(nm(1/Math.PI)).mul(e.pow(Km)))),Gb=Zf((({lightDirection:e})=>{const t=e.add($v).normalize(),n=ny.dot(t).clamp(),i=$v.dot(t).clamp(),r=Bb({f0:$m,f90:1,dotVH:i}),s=nm(.25),a=zb({dotNH:n});return r.mul(s).mul(a)}));class Vb extends Ib{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=ny.dot(e).clamp().mul(t);n.directDiffuse.addAssign(i.mul(kb({diffuseColor:Um.rgb}))),!0===this.specular&&n.directSpecular.addAssign(i.mul(Gb({lightDirection:e})).mul(qy))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(kb({diffuseColor:Um}))),i.indirectDiffuse.mulAssign(t)}}const Hb=new Cs;class jb extends _b{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Hb),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Db(t):null}setupLightingModel(){return new Vb(!1)}}const Wb=new ws;class Xb extends _b{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Wb),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Db(t):null}setupLightingModel(){return new Vb}setupVariants(){const e=(this.shininessNode?nm(this.shininessNode):Gy).max(1e-4);Km.assign(e);const t=this.specularNode||jy;$m.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const qb=Zf((e=>{if(!1===e.geometry.hasAttribute("normal"))return nm(0);const t=ey.dFdx().abs().max(ey.dFdy().abs());return t.x.max(t.y).max(t.z)})),$b=Zf((e=>{const{roughness:t}=e,n=qb();let i=t.max(.0525);return i=i.add(n),i=i.min(1),i})),Yb=Zf((({alpha:e,dotNL:t,dotNV:n})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(n.pow2())).sqrt()),s=n.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return dg(.5,r.add(s).max(Pg))})).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Kb=Zf((({alphaT:e,alphaB:t,dotTV:n,dotBV:i,dotTL:r,dotBL:s,dotNV:a,dotNL:o})=>{const l=o.mul(cm(e.mul(n),t.mul(i),a).length()),u=a.mul(cm(e.mul(r),t.mul(s),o).length());return dg(.5,l.add(u)).saturate()})).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),Zb=Zf((({alpha:e,dotNH:t})=>{const n=e.pow2(),i=t.pow2().mul(n.oneMinus()).oneMinus();return n.div(i.pow2()).mul(1/Math.PI)})).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),Qb=nm(1/Math.PI),Jb=Zf((({alphaT:e,alphaB:t,dotNH:n,dotTH:i,dotBH:r})=>{const s=e.mul(t),a=cm(t.mul(i),e.mul(r),s.mul(n)),o=a.dot(a),l=s.div(o);return Qb.mul(s.mul(l.pow2()))})).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),eS=Zf((e=>{const{lightDirection:t,f0:n,f90:i,roughness:r,f:s,USE_IRIDESCENCE:a,USE_ANISOTROPY:o}=e,l=e.normalView||ny,u=r.pow2(),c=t.add($v).normalize(),h=l.dot(t).clamp(),d=l.dot($v).clamp(),p=l.dot(c).clamp(),f=$v.dot(c).clamp();let m,g,_=Bb({f0:n,f90:i,dotVH:f});if(jf(a)&&(_=Gm.mix(_,s)),jf(o)){const e=Xm.dot(t),n=Xm.dot($v),i=Xm.dot(c),r=qm.dot(t),s=qm.dot($v),a=qm.dot(c);m=Kb({alphaT:jm,alphaB:u,dotTV:n,dotBV:s,dotTL:e,dotBL:r,dotNV:d,dotNL:h}),g=Jb({alphaT:jm,alphaB:u,dotNH:p,dotTH:i,dotBH:a})}else m=Yb({alpha:u,dotNL:h,dotNV:d}),g=Zb({alpha:u,dotNH:p});return _.mul(m).mul(g)})),tS=Zf((({roughness:e,dotNV:t})=>{const n=fm(-1,-.0275,-.572,.022),i=fm(1,.0425,1.04,-.04),r=e.mul(n).add(i),s=r.x.mul(r.x).min(t.mul(-9.28).exp2()).mul(r.x).add(r.y);return am(-1.04,1.04).mul(s).add(r.zw)})).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),nS=Zf((e=>{const{dotNV:t,specularColor:n,specularF90:i,roughness:r}=e,s=tS({dotNV:t,roughness:r});return n.mul(s.x).add(i.mul(s.y))})),iS=Zf((({f:e,f90:t,dotVH:n})=>{const i=n.oneMinus().saturate(),r=i.mul(i),s=i.mul(r,r).clamp(0,.9999);return e.sub(cm(t).mul(s)).div(s.oneMinus())})).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),rS=Zf((({roughness:e,dotNH:t})=>{const n=e.pow2(),i=nm(1).div(n),r=t.pow2().oneMinus().max(.0078125);return nm(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)})).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),sS=Zf((({dotNV:e,dotNL:t})=>nm(1).div(nm(4).mul(t.add(e).sub(t.mul(e)))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),aS=Zf((({lightDirection:e})=>{const t=e.add($v).normalize(),n=ny.dot(e).clamp(),i=ny.dot($v).clamp(),r=ny.dot(t).clamp(),s=rS({roughness:zm,dotNH:r}),a=sS({dotNV:i,dotNL:n});return km.mul(s).mul(a)})),oS=Zf((({N:e,V:t,roughness:n})=>{const i=e.dot(t).saturate(),r=am(n,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r})).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),lS=Zf((({f:e})=>{const t=e.length();return p_(t.mul(t).add(e.z).div(t.add(1)),0)})).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),uS=Zf((({v1:e,v2:t})=>{const n=e.dot(t),i=n.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),s=i.add(4.1616724).mul(i).add(3.417594).toVar(),a=r.div(s),o=n.greaterThan(0).select(a,p_(n.mul(n).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)})).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),cS=Zf((({N:e,V:t,P:n,mInv:i,p0:r,p1:s,p2:a,p3:o})=>{const l=s.sub(r).toVar(),u=o.sub(r).toVar(),c=l.cross(u),h=cm().toVar();return em(c.dot(n.sub(r)).greaterThanEqual(0),(()=>{const l=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(l).negate(),c=i.mul(ym(l,u,e).transpose()).toVar(),d=c.mul(r.sub(n)).normalize().toVar(),p=c.mul(s.sub(n)).normalize().toVar(),f=c.mul(a.sub(n)).normalize().toVar(),m=c.mul(o.sub(n)).normalize().toVar(),g=cm(0).toVar();g.addAssign(uS({v1:d,v2:p})),g.addAssign(uS({v1:p,v2:f})),g.addAssign(uS({v1:f,v2:m})),g.addAssign(uS({v1:m,v2:d})),h.assign(cm(lS({f:g})))})),h})).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),hS=1/6,dS=e=>hg(hS,hg(e,hg(e,e.negate().add(3)).sub(3)).add(1)),pS=e=>hg(hS,hg(e,hg(e,hg(3,e).sub(6))).add(4)),fS=e=>hg(hS,hg(e,hg(e,hg(-3,e).add(3)).add(3)).add(1)),mS=e=>hg(hS,b_(e,3)),gS=e=>dS(e).add(pS(e)),_S=e=>fS(e).add(mS(e)),vS=e=>ug(-1,pS(e).div(dS(e).add(pS(e)))),yS=e=>ug(1,mS(e).div(fS(e).add(mS(e)))),xS=(e,t,n)=>{const i=e.uvNode,r=hg(i,t.zw).add(.5),s=Hg(r),a=Xg(r),o=gS(a.x),l=_S(a.x),u=vS(a.x),c=yS(a.x),h=vS(a.y),d=yS(a.y),p=am(s.x.add(u),s.y.add(h)).sub(.5).mul(t.xy),f=am(s.x.add(c),s.y.add(h)).sub(.5).mul(t.xy),m=am(s.x.add(u),s.y.add(d)).sub(.5).mul(t.xy),g=am(s.x.add(c),s.y.add(d)).sub(.5).mul(t.xy),_=gS(a.y).mul(ug(o.mul(e.sample(p).level(n)),l.mul(e.sample(f).level(n)))),v=_S(a.y).mul(ug(o.mul(e.sample(m).level(n)),l.mul(e.sample(g).level(n))));return _.add(v)},bS=Zf((([e,t=nm(3)])=>{const n=am(e.size(im(t))),i=am(e.size(im(t.add(1)))),r=dg(1,n),s=dg(1,i),a=xS(e,fm(r,n),Hg(t)),o=xS(e,fm(s,i),jg(t));return Xg(t).mix(a,o)})),SS=Zf((([e,t,n,i,r])=>{const s=cm(C_(t.negate(),Wg(e),dg(1,i))),a=cm(t_(r[0].xyz),t_(r[1].xyz),t_(r[2].xyz));return Wg(s).mul(n.mul(a))})).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),TS=Zf((([e,t])=>e.mul(R_(t.mul(2).sub(2),0,1)))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),MS=tb(),ES=tb(),wS=Zf((([e,t,n],{material:i})=>{const r=(1===i.side?MS:ES).sample(e),s=zg(Kx.x).mul(TS(t,n));return bS(r,s)})),AS=Zf((([e,t,n])=>(em(n.notEqual(0),(()=>{const i=kg(t).negate().div(n);return Fg(i.negate().mul(e))})),cm(1)))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),RS=Zf((([e,t,n,i,r,s,a,o,l,u,c,h,d,p,f])=>{let m,g;if(f){m=fm().toVar(),g=cm().toVar();const r=c.sub(1).mul(f.mul(.025)),s=cm(c.sub(r),c,c.add(r));Ix({start:0,end:3},(({i:r})=>{const c=s.element(r),f=SS(e,t,h,c,o),_=a.add(f),v=u.mul(l.mul(fm(_,1))),y=am(v.xy.div(v.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(am(y.x,y.y.oneMinus()));const x=wS(y,n,c);m.element(r).assign(x.element(r)),m.a.addAssign(x.a),g.element(r).assign(i.element(r).mul(AS(t_(f),d,p).element(r)))})),m.a.divAssign(3)}else{const r=SS(e,t,h,c,o),s=a.add(r),f=u.mul(l.mul(fm(s,1))),_=am(f.xy.div(f.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(am(_.x,_.y.oneMinus())),m=wS(_,n,c),g=i.mul(AS(t_(r),d,p))}const _=g.rgb.mul(m.rgb),v=e.dot(t).clamp(),y=cm(nS({dotNV:v,specularColor:r,specularF90:s,roughness:n})),x=g.r.add(g.g,g.b).div(3);return fm(y.oneMinus().mul(_),m.a.oneMinus().mul(x).oneMinus())})),CS=ym(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),NS=(e,t)=>e.sub(t).div(e.add(t)).pow2(),PS=Zf((({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:i,baseF0:r})=>{const s=A_(e,t,N_(0,.03,i)),a=e.div(s).pow2().mul(n.pow2().oneMinus()).oneMinus();em(a.lessThan(0),(()=>cm(1)));const o=a.sqrt(),l=NS(s,e),u=Bb({f0:l,f90:1,dotVH:n}),c=u.oneMinus(),h=s.lessThan(e).select(Math.PI,0),d=nm(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return cm(1).add(t).div(cm(1).sub(t))})(r.clamp(0,.9999)),f=NS(p,s.toVec3()),m=Bb({f0:f,f90:1,dotVH:o}),g=cm(p.x.lessThan(s).select(Math.PI,0),p.y.lessThan(s).select(Math.PI,0),p.z.lessThan(s).select(Math.PI,0)),_=s.mul(i,o,2),v=cm(d).add(g),y=u.mul(m).clamp(1e-5,.9999),x=y.sqrt(),b=c.pow2().mul(m).div(cm(1).sub(y)),S=u.add(b).toVar(),T=b.sub(c).toVar();return Ix({start:1,end:2,condition:"<=",name:"m"},(({m:e})=>{T.mulAssign(x);const t=((e,t)=>{const n=e.mul(2*Math.PI*1e-9),i=cm(54856e-17,44201e-17,52481e-17),r=cm(1681e3,1795300,2208400),s=cm(43278e5,93046e5,66121e5),a=nm(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(n.mul(2239900).add(t.x).cos()).mul(n.pow2().mul(-45282e5).exp());let o=i.mul(s.mul(2*Math.PI).sqrt()).mul(r.mul(n).add(t).cos()).mul(n.pow2().negate().mul(s).exp());return o=cm(o.x.add(a),o.y,o.z).div(1.0685e-7),CS.mul(o)})(nm(e).mul(_),nm(e).mul(v)).mul(2);S.addAssign(T.mul(t))})),S.max(cm(0))})).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),DS=Zf((({normal:e,viewDir:t,roughness:n})=>{const i=e.dot(t).saturate(),r=n.pow2(),s=L_(n.lessThan(.25),nm(-339.2).mul(r).add(nm(161.4).mul(n)).sub(25.9),nm(-8.48).mul(r).add(nm(14.3).mul(n)).sub(9.95)),a=L_(n.lessThan(.25),nm(44).mul(r).sub(nm(23.7).mul(n)).add(3.26),nm(1.97).mul(r).sub(nm(3.27).mul(n)).add(.72));return L_(n.lessThan(.25),0,nm(.1).mul(n).sub(.025)).add(s.mul(i).add(a).exp()).mul(1/Math.PI).saturate()})),US=cm(.04),LS=nm(1);class IS extends Lb{constructor(e=!1,t=!1,n=!1,i=!1,r=!1,s=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=i,this.transmission=r,this.dispersion=s,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=cm().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=cm().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=cm().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=cm().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=cm().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=ny.dot($v).clamp();this.iridescenceFresnel=PS({outsideIOR:nm(1),eta2:Vm,cosTheta1:e,thinFilmThickness:Hm,baseF0:$m}),this.iridescenceF0=iS({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=Wv,n=Uv.sub(Wv).normalize(),i=iy,r=e.context;r.backdrop=RS(i,n,Im,Um,$m,Ym,t,Bv,Dv,Pv,eg,ng,rg,ig,this.dispersion?sg:null),r.backdropAlpha=tg,Um.a.mulAssign(A_(1,r.backdrop.a,tg))}super.start(e)}computeMultiscattering(e,t,n){const i=ny.dot($v).clamp(),r=tS({roughness:Im,dotNV:i}),s=(this.iridescenceF0?Gm.mix($m,this.iridescenceF0):$m).mul(r.x).add(n.mul(r.y)),a=r.x.add(r.y).oneMinus(),o=$m.add($m.oneMinus().mul(.047619)),l=s.mul(o).div(a.mul(o).oneMinus());e.addAssign(s),t.addAssign(l.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const i=ny.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(i.mul(aS({lightDirection:e}))),!0===this.clearcoat){const n=ry.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(eS({lightDirection:e,f0:US,f90:LS,roughness:Bm,normalView:ry})))}n.directDiffuse.addAssign(i.mul(kb({diffuseColor:Um.rgb}))),n.directSpecular.addAssign(i.mul(eS({lightDirection:e,f0:$m,f90:1,roughness:Im,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:i,reflectedLight:r,ltc_1:s,ltc_2:a}){const o=t.add(n).sub(i),l=t.sub(n).sub(i),u=t.sub(n).add(i),c=t.add(n).add(i),h=ny,d=$v,p=qv.toVar(),f=oS({N:h,V:d,roughness:Im}),m=s.sample(f).toVar(),g=a.sample(f).toVar(),_=ym(cm(m.x,0,m.y),cm(0,1,0),cm(m.z,0,m.w)).toVar(),v=$m.mul(g.x).add($m.oneMinus().mul(g.y)).toVar();r.directSpecular.addAssign(e.mul(v).mul(cS({N:h,V:d,P:p,mInv:_,p0:o,p1:l,p2:u,p3:c}))),r.directDiffuse.addAssign(e.mul(Um).mul(cS({N:h,V:d,P:p,mInv:ym(1,0,0,0,1,0,0,0,1),p0:o,p1:l,p2:u,p3:c})))}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:n}=e.context;n.indirectDiffuse.addAssign(t.mul(kb({diffuseColor:Um})))}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(n.mul(km,DS({normal:ny,viewDir:$v,roughness:zm}))),!0===this.clearcoat){const e=ry.dot($v).clamp(),t=nS({dotNV:e,specularColor:US,specularF90:LS,roughness:Bm});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=cm().toVar("singleScattering"),s=cm().toVar("multiScattering"),a=n.mul(1/Math.PI);this.computeMultiscattering(r,s,Ym);const o=r.add(s),l=Um.mul(o.r.max(o.g).max(o.b).oneMinus());i.indirectSpecular.addAssign(t.mul(r)),i.indirectSpecular.addAssign(s.mul(a)),i.indirectDiffuse.addAssign(l.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,i=ny.dot($v).clamp().add(t),r=Im.mul(-16).oneMinus().negate().exp2(),s=t.sub(i.pow(r).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(s)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=ry.dot($v).clamp(),n=Bb({dotVH:e,f0:US,f90:LS}),i=t.mul(Fm.mul(n).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Fm));t.assign(i)}if(!0===this.sheen){const e=km.r.max(km.g).max(km.b).mul(.157).oneMinus(),n=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(n)}}}const OS=nm(1),FS=nm(-2),BS=nm(.8),kS=nm(-1),zS=nm(.4),GS=nm(2),VS=nm(.305),HS=nm(3),jS=nm(.21),WS=nm(4),XS=nm(4),qS=nm(16),$S=Zf((([e])=>{const t=cm(Jg(e)).toVar(),n=nm(-1).toVar();return em(t.x.greaterThan(t.z),(()=>{em(t.x.greaterThan(t.y),(()=>{n.assign(L_(e.x.greaterThan(0),0,3))})).Else((()=>{n.assign(L_(e.y.greaterThan(0),1,4))}))})).Else((()=>{em(t.z.greaterThan(t.y),(()=>{n.assign(L_(e.z.greaterThan(0),2,5))})).Else((()=>{n.assign(L_(e.y.greaterThan(0),1,4))}))})),n})).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),YS=Zf((([e,t])=>{const n=am().toVar();return em(t.equal(0),(()=>{n.assign(am(e.z,e.y).div(Jg(e.x)))})).ElseIf(t.equal(1),(()=>{n.assign(am(e.x.negate(),e.z.negate()).div(Jg(e.y)))})).ElseIf(t.equal(2),(()=>{n.assign(am(e.x.negate(),e.y).div(Jg(e.z)))})).ElseIf(t.equal(3),(()=>{n.assign(am(e.z.negate(),e.y).div(Jg(e.x)))})).ElseIf(t.equal(4),(()=>{n.assign(am(e.x.negate(),e.z).div(Jg(e.y)))})).Else((()=>{n.assign(am(e.x,e.y).div(Jg(e.z)))})),hg(.5,n.add(1))})).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),KS=Zf((([e])=>{const t=nm(0).toVar();return em(e.greaterThanEqual(BS),(()=>{t.assign(OS.sub(e).mul(kS.sub(FS)).div(OS.sub(BS)).add(FS))})).ElseIf(e.greaterThanEqual(zS),(()=>{t.assign(BS.sub(e).mul(GS.sub(kS)).div(BS.sub(zS)).add(kS))})).ElseIf(e.greaterThanEqual(VS),(()=>{t.assign(zS.sub(e).mul(HS.sub(GS)).div(zS.sub(VS)).add(GS))})).ElseIf(e.greaterThanEqual(jS),(()=>{t.assign(VS.sub(e).mul(WS.sub(HS)).div(VS.sub(jS)).add(HS))})).Else((()=>{t.assign(nm(-2).mul(zg(hg(1.16,e))))})),t})).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),ZS=Zf((([e,t])=>{const n=e.toVar();n.assign(hg(2,n).sub(1));const i=cm(n,1).toVar();return em(t.equal(0),(()=>{i.assign(i.zyx)})).ElseIf(t.equal(1),(()=>{i.assign(i.xzy),i.xz.mulAssign(-1)})).ElseIf(t.equal(2),(()=>{i.x.mulAssign(-1)})).ElseIf(t.equal(3),(()=>{i.assign(i.zyx),i.xz.mulAssign(-1)})).ElseIf(t.equal(4),(()=>{i.assign(i.xzy),i.xy.mulAssign(-1)})).ElseIf(t.equal(5),(()=>{i.z.mulAssign(-1)})),i})).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),QS=Zf((([e,t,n,i,r,s])=>{const a=nm(n),o=cm(t),l=R_(KS(a),FS,s),u=Xg(l),c=Hg(l),h=cm(JS(e,o,c,i,r,s)).toVar();return em(u.notEqual(0),(()=>{const t=cm(JS(e,o,c.add(1),i,r,s)).toVar();h.assign(A_(h,t,u))})),h})),JS=Zf((([e,t,n,i,r,s])=>{const a=nm(n).toVar(),o=cm(t),l=nm($S(o)).toVar(),u=nm(p_(XS.sub(a),0)).toVar();a.assign(p_(a,XS));const c=nm(Bg(a)).toVar(),h=am(YS(o,l).mul(c.sub(2)).add(1)).toVar();return em(l.greaterThan(2),(()=>{h.y.addAssign(c),l.subAssign(3)})),h.x.addAssign(l.mul(c)),h.x.addAssign(u.mul(hg(3,qS))),h.y.addAssign(hg(4,Bg(s).sub(c))),h.x.mulAssign(i),h.y.mulAssign(r),e.sample(h).grad(am(),am())})),eT=Zf((({envMap:e,mipInt:t,outputDirection:n,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=$g(i),u=n.mul(l).add(r.cross(n).mul(qg(i))).add(r.mul(r.dot(n).mul(l.oneMinus())));return JS(e,u,t,s,a,o)})),tT=Zf((({n:e,latitudinal:t,poleAxis:n,outputDirection:i,weights:r,samples:s,dTheta:a,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})=>{const d=cm(L_(t,n,x_(n,i))).toVar();em(Ug(d.equals(cm(0))),(()=>{d.assign(cm(i.z,0,i.x.negate()))})),d.assign(Wg(d));const p=cm().toVar();return p.addAssign(r.element(0).mul(eT({theta:0,axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),Ix({start:im(1),end:e},(({i:e})=>{em(e.greaterThanEqual(s),(()=>{hv("break").append()}));const t=nm(a.mul(nm(e))).toVar();p.addAssign(r.element(e).mul(eT({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),p.addAssign(r.element(e).mul(eT({theta:t,axis:d,outputDirection:i,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})))})),fm(p,1)})),nT=[.125,.215,.35,.446,.526,.582],iT=20,rT=new Qs(-1,1,1,-1,0,1),sT=new Er(90,1),aT=new Pi;let oT=null,lT=0,uT=0;const cT=(1+Math.sqrt(5))/2,hT=1/cT,dT=[new un(-cT,hT,0),new un(cT,hT,0),new un(-hT,0,cT),new un(hT,0,cT),new un(0,cT,-hT),new un(0,cT,hT),new un(-1,1,-1),new un(1,1,-1),new un(-1,1,1),new un(1,1,1)],pT=new un,fT=new WeakMap,mT=[3,1,5,0,4,2],gT=ZS(mv(),fv("faceIndex")).normalize(),_T=cm(gT.x,gT.y,gT.z);class vT{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,i=100,r={}){const{size:s=256,position:a=pT,renderTarget:o=null}=r;if(this._setSize(s),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const s=o||this._allocateTargets();return r.renderTarget=s,this.fromSceneAsync(e,t,n,i,r),s}oT=this._renderer.getRenderTarget(),lT=this._renderer.getActiveCubeFace(),uT=this._renderer.getActiveMipmapLevel();const l=o||this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,n,i,l,a),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,n=.1,i=100,r={}){return!1===this._hasInitialized&&await this._renderer.init(),this.fromScene(e,t,n,i,r)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const n=t||this._allocateTargets();return this.fromEquirectangularAsync(e,n),n}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const n=t||this._allocateTargets();return this.fromCubemapAsync(e,t),n}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=ST(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=TT(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===V||e.mapping===H?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?l=nT[o-e+4-1]:0===o&&(l=0),i.push(l);const u=1/(a-2),c=-u,h=1+u,d=[c,c,h,c,h,h,c,c,h,h,c,h],p=6,f=6,m=3,g=2,_=1,v=new Float32Array(m*f*p),y=new Float32Array(g*f*p),x=new Float32Array(_*f*p);for(let e=0;e2?0:-1,i=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0],r=mT[e];v.set(i,m*f*r),y.set(d,g*f*r);const s=[r,r,r,r,r,r];x.set(s,_*f*r)}const b=new tr;b.setAttribute("position",new Hi(v,m)),b.setAttribute("uv",new Hi(y,g)),b.setAttribute("faceIndex",new Hi(x,_)),t.push(b),r.push(new pr(b,null)),s>4&&s--}return{lodPlanes:t,sizeLods:n,sigmas:i,lodMeshes:r}}(i)),this._blurMaterial=function(e,t,n){const i=Av(new Array(iT).fill(0)),r=Cm(new un(0,1,0)),s=Cm(0),a=nm(iT),o=Cm(0),l=Cm(1),u=bv(null),c=Cm(0),h=nm(1/t),d=nm(1/n),p=nm(e),f={n:a,latitudinal:o,weights:i,poleAxis:r,outputDirection:_T,dTheta:s,samples:l,envMap:u,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},m=bT("blur");return m.fragmentNode=tT({...f,latitudinal:o.equal(1)}),fT.set(m,f),m}(i,e,t)}return i}async _compileMaterial(e){const t=new pr(this._lodPlanes[0],e);await this._renderer.compile(t,rT)}_sceneToCubeUV(e,t,n,i,r){const s=sT;s.near=t,s.far=n;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],l=this._renderer,u=l.autoClear;l.getClearColor(aT),l.autoClear=!1;let c=this._backgroundBox;if(null===c){const e=new Ii({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1});c=new pr(new mr,e)}let h=!1;const d=e.background;d?d.isColor&&(c.material.color.copy(d),e.background=null,h=!0):(c.material.color.copy(aT),h=!0),l.setRenderTarget(i),l.clear(),h&&l.render(c,s);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x+o[t],r.y,r.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y+o[t],r.z)):(s.up.set(0,a[t],0),s.position.set(r.x,r.y,r.z),s.lookAt(r.x,r.y,r.z+o[t]));const u=this._cubeSize;xT(i,n*u,t>2?u:0,u,u),l.render(e,s)}l.autoClear=u,e.background=d}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===V||e.mapping===H;i?null===this._cubemapMaterial&&(this._cubemapMaterial=ST(e)):null===this._equirectMaterial&&(this._equirectMaterial=TT(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const s=this._lodMeshes[0];s.material=r;const a=this._cubeSize;xT(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,rT)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodPlanes.length;for(let t=1;tiT&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let e=0;e_-4?i-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,rT)}}function yT(e,t,n){const i=new rn(e,t,n);return i.texture.mapping=X,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function xT(e,t,n,i,r){e.viewport.set(t,n,i,r),e.scissor.set(t,n,i,r)}function bT(e){const t=new _b;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function ST(e){const t=bT("cubemap");return t.fragmentNode=_y(e,_T),t}function TT(e){const t=bT("equirect");return t.fragmentNode=bv(e,Eb(_T),0),t}const MT=new WeakMap;function ET(e,t,n){const i=function(e){let t=MT.get(e);void 0===t&&(t=new WeakMap,MT.set(e,t));return t}(t);let r=i.get(e);if((void 0!==r?r.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const n=6;for(let i=0;i0}(t))return null;r=n.fromEquirectangular(e,r)}r.pmremVersion=e.pmremVersion,i.set(e,r)}return r.texture}class wT extends lf{static get type(){return"PMREMNode"}constructor(e,t=null,n=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=n,this._generator=null;const i=new tn;i.isRenderTargetTexture=!0,this._texture=bv(i),this._width=Cm(0),this._height=Cm(0),this._maxMip=Cm(0),this.updateBeforeType=Yp}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=function(e){const t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const n=t?t.pmremVersion:-1,i=this._value;n!==i.pmremVersion&&(t=!0===i.isPMREMTexture?i:ET(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new vT(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=hy.mul(cm(t.x,t.y.negate(),t.z));let n=this.levelNode;return null===n&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),QS(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const AT=Yf(wT),RT=new WeakMap;class CT extends Gx{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){const e=n.isTextureNode?n.value:t[n.property];let i=RT.get(e);void 0===i&&(i=AT(e),RT.set(e,i)),n=i}const i=!0===t.useAnisotropy||t.anisotropy>0?Cy:ny,r=n.context(NT(Im,i)).mul(cy),s=n.context(PT(iy)).mul(Math.PI).mul(cy),a=sv(r),o=sv(s);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=n.context(NT(Bm,ry)).mul(cy),t=sv(e);l.addAssign(t)}}}const NT=(e,t)=>{let n=null;return{getUV:()=>(null===n&&(n=$v.negate().reflect(t),n=e.mul(e).mix(n,t).normalize(),n=n.transformDirection(Dv)),n),getTextureLevel:()=>e}},PT=e=>({getUV:()=>e,getTextureLevel:()=>nm(1)}),DT=new Ms;class UT extends _b{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(DT),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new CT(t):null}setupLightingModel(){return new IS}setupSpecular(){const e=A_(cm(.04),Um.rgb,Om);$m.assign(e),Ym.assign(1)}setupVariants(){const e=this.metalnessNode?nm(this.metalnessNode):Ky;Om.assign(e);let t=this.roughnessNode?nm(this.roughnessNode):Yy;t=$b({roughness:t}),Im.assign(t),this.setupSpecular(),Um.assign(fm(Um.rgb.mul(e.oneMinus()),Um.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const LT=new Es;class IT extends UT{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(LT),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?nm(this.iorNode):cx;eg.assign(e),$m.assign(A_(d_(S_(eg.sub(1).div(eg.add(1))).mul(Xy),cm(1)).mul(Wy),Um.rgb,Om)),Ym.assign(A_(Wy,1,Om))}setupLightingModel(){return new IS(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?nm(this.clearcoatNode):Qy,t=this.clearcoatRoughnessNode?nm(this.clearcoatRoughnessNode):Jy;Fm.assign(e),Bm.assign($b({roughness:t}))}if(this.useSheen){const e=this.sheenNode?cm(this.sheenNode):nx,t=this.sheenRoughnessNode?nm(this.sheenRoughnessNode):ix;km.assign(e),zm.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?nm(this.iridescenceNode):sx,t=this.iridescenceIORNode?nm(this.iridescenceIORNode):ax,n=this.iridescenceThicknessNode?nm(this.iridescenceThicknessNode):ox;Gm.assign(e),Vm.assign(t),Hm.assign(n)}if(this.useAnisotropy){const e=(this.anisotropyNode?am(this.anisotropyNode):rx).toVar();Wm.assign(e.length()),em(Wm.equal(0),(()=>{e.assign(am(1,0))})).Else((()=>{e.divAssign(am(Wm)),Wm.assign(Wm.saturate())})),jm.assign(Wm.pow2().mix(Im.pow2(),1)),Xm.assign(Ry[0].mul(e.x).add(Ry[1].mul(e.y))),qm.assign(Ry[1].mul(e.x).sub(Ry[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?nm(this.transmissionNode):lx,t=this.thicknessNode?nm(this.thicknessNode):ux,n=this.attenuationDistanceNode?nm(this.attenuationDistanceNode):hx,i=this.attenuationColorNode?cm(this.attenuationColorNode):dx;if(tg.assign(e),ng.assign(t),ig.assign(n),rg.assign(i),this.useDispersion){const e=this.dispersionNode?nm(this.dispersionNode):vx;sg.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?cm(this.clearcoatNormalNode):ex}setup(e){e.context.setupClearcoatNormal=()=>this.setupClearcoatNormal(e),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const OT=Zf((({normal:e,lightDirection:t,builder:n})=>{const i=e.dot(t),r=am(i.mul(.5).add(.5),0);if(n.material.gradientMap){const e=Ty("gradientMap","texture").context({getUV:()=>r});return cm(e.r)}{const e=r.fwidth().mul(.5);return A_(cm(.7),cm(1),N_(nm(.7).sub(e.x),nm(.7).add(e.x),r.x))}}));class FT extends Lb{direct({lightDirection:e,lightColor:t,reflectedLight:n},i){const r=OT({normal:Zv,lightDirection:e,builder:i}).mul(t);n.directDiffuse.addAssign(r.mul(kb({diffuseColor:Um.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(kb({diffuseColor:Um}))),i.indirectDiffuse.mulAssign(t)}}const BT=new As;class kT extends _b{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(BT),this.setValues(e)}setupLightingModel(){return new FT}}class zT extends lf{static get type(){return"MatcapUVNode"}constructor(){super("vec2")}setup(){const e=cm($v.z,0,$v.x.negate()).normalize(),t=$v.cross(e);return am(e.dot(ny),t.dot(ny)).mul(.495).add(.5)}}const GT=Kf(zT),VT=new Ds;class HT extends _b{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(VT),this.setValues(e)}setupVariants(e){const t=GT;let n;n=e.material.matcap?Ty("matcap","texture").context({getUV:()=>t}):cm(A_(.2,.8,t.y)),Um.rgb.mulAssign(n.rgb)}}class jT extends lf{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return vm(e,i,i.negate(),e).mul(n)}{const e=t,i=xm(fm(1,0,0,0),fm(0,$g(e.x),qg(e.x).negate(),0),fm(0,qg(e.x),$g(e.x),0),fm(0,0,0,1)),r=xm(fm($g(e.y),0,qg(e.y),0),fm(0,1,0,0),fm(qg(e.y).negate(),0,$g(e.y),0),fm(0,0,0,1)),s=xm(fm($g(e.z),qg(e.z).negate(),0,0),fm(qg(e.z),$g(e.z),0,0),fm(0,0,1,0),fm(0,0,0,1));return i.mul(r).mul(s).mul(fm(n,1)).xyz}}}const WT=Yf(jT),XT=new Fr;class qT extends _b{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(XT),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,i=this.sizeAttenuation,{positionNode:r,rotationNode:s,scaleNode:a}=this,o=zv.mul(cm(r||0));let l=am(Bv[0].xyz.length(),Bv[1].xyz.length());if(null!==a&&(l=l.mul(am(a))),!1===i)if(n.isPerspectiveCamera)l=l.mul(o.z.negate());else{const e=nm(2).div(Pv.element(1).element(1));l=l.mul(e.mul(2))}let u=Vv.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,n)=>Xf(new $_(e,t,n)))("center","vec2",t);u=u.sub(e.sub(.5))}u=u.mul(l);const c=nm(s||tx),h=WT(u,c);return fm(o.xy.add(h),o.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const $T=new ns;class YT extends qT{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues($T),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return zv.mul(cm(e||Hv)).xyz}setupVertex(e){const t=super.setupVertex(e);if(!0!==e.material.isNodeMaterial)return t;const{rotationNode:n,scaleNode:i,sizeNode:r}=this,s=Vv.xy.toVar(),a=Qx.z.div(Qx.w);if(n&&n.isNode){const e=nm(n);s.assign(WT(s,e))}let o=null!==r?am(r):_x;return!0===this.sizeAttenuation&&(o=o.mul(o.div(qv.z.negate()))),i&&i.isNode&&(o=o.mul(am(i))),s.mulAssign(o.mul(2)),s.assign(s.div(Qx.z)),s.y.assign(s.y.mul(a)),s.assign(s.mul(t.w)),t.addAssign(fm(s,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class KT extends Lb{constructor(){super(),this.shadowNode=nm(1).toVar("shadowMask")}direct({shadowMask:e}){this.shadowNode.mulAssign(e)}finish(e){Um.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Um.rgb)}}const ZT=new Ts;class QT extends _b{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.setDefaultValues(ZT),this.setValues(e)}setupLightingModel(){return new KT}}Pm("vec3"),Pm("vec3"),Pm("vec3");class JT{constructor(e,t){this.nodes=e,this.info=t,this._context=self,this._animationLoop=null,this._requestId=null}start(){const e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,null!==this._animationLoop&&this._animationLoop(t,n)};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class eM{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let n=0;n{this.dispose()},this.material.addEventListener("dispose",this.onMaterialDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],i=new Set;for(const r of e){const e=r.node&&r.node.attribute?r.node.attribute:t.getAttribute(r.name);if(void 0===e)continue;n.push(e);const s=e.isInterleavedBufferAttribute?e.data:e;i.add(s)}return this.attributes=n,this.vertexBuffers=Array.from(i.values()),n}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:n,group:i,drawRange:r}=this,s=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a,l=n.isInstancedBufferGeometry?n.instanceCount:e.count>1?e.count:1;if(0===l)return null;if(s.instanceCount=l,!0===e.isBatchedMesh)return s;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let c=r.start*u,h=(r.start+r.count)*u;null!==i&&(c=Math.max(c,i.start*u),h=Math.min(h,(i.start+i.count)*u));const d=n.attributes.position;let p=1/0;o?p=a.count:null!=d&&(p=d.count),c=Math.max(c,0),h=Math.min(h,p);const f=h-c;return f<0||f===1/0?null:(s.vertexCount=f,s.firstVertex=c,s)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const n of Object.keys(e.attributes).sort()){const i=e.attributes[n];t+=n+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const n of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[n];t+="morph-"+n+",";for(let e=0,n=i.length;e1&&(n+=e.uuid+","),n+=e.receiveShadow+",",Op(n)}get needsGeometryUpdate(){return this.geometry.id!==this.object.geometry.id}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Bp(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Bp(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const iM=[];class rM{constructor(e,t,n,i,r,s){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=i,this.bindings=r,this.info=s,this.chainMaps={}}get(e,t,n,i,r,s,a,o){const l=this.getChainMap(o);iM[0]=e,iM[1]=t,iM[2]=s,iM[3]=r;let u=l.get(iM);return void 0===u?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,i,r,s,a,o),l.set(iM,u)):(u.updateClipping(a),u.needsGeometryUpdate&&u.setGeometry(e.geometry),(u.version!==t.version||u.needsUpdate)&&(u.initialCacheKey!==u.getCacheKey()?(u.dispose(),u=this.get(e,t,n,i,r,s,a,o)):u.version=t.version)),iM.length=0,u}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new eM)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,i,r,s,a,o,l,u,c){const h=this.getChainMap(c),d=new nM(e,t,n,i,r,s,a,o,l,u);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.delete(d),this.nodes.delete(d),h.delete(d.getChainArray())},d}}class sM{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const aM=1,oM=2,lM=3,uM=4,cM=16;class hM extends sM{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return void 0!==t&&this.backend.destroyAttribute(e),t}update(e,t){const n=this.get(e);if(void 0===n.version)t===aM?this.backend.createAttribute(e):t===oM?this.backend.createIndexAttribute(e):t===lM?this.backend.createStorageAttribute(e):t===uM&&this.backend.createIndirectStorageAttribute(e),n.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(n.version{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const s=this.wireframes.get(t);void 0!==s&&this.attributes.delete(s),t.removeEventListener("dispose",n)};t.addEventListener("dispose",n)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,lM):this.updateAttribute(e,aM);const n=this.getIndex(e);null!==n&&this.updateAttribute(n,oM);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,uM)}updateAttribute(e,t){const n=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,n)):this.attributeCall.get(e.data)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e.data,n),this.attributeCall.set(e,n)):this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:n}=e;let i=t.index;if(!0===n.wireframe){const e=this.wireframes;let n=e.get(t);void 0===n?(n=pM(t),e.set(t,n)):n.version!==dM(t)&&(this.attributes.delete(n),n=pM(t),e.set(t,n)),i=n}return i}}class mM{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine?this.render.lines+=n*(t-1):console.error("THREE.WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class gM{constructor(e){this.cacheKey=e,this.usedTimes=0}}class _M extends gM{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class vM extends gM{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let yM=0;class xM{constructor(e,t,n,i=null,r=null){this.id=yM++,this.code=e,this.stage=t,this.name=n,this.transforms=i,this.attributes=r,this.usedTimes=0}}class bM extends sM{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:n}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const s=this.nodes.getForCompute(e);let a=this.programs.compute.get(s.computeShader);void 0===a&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),a=new xM(s.computeShader,"compute",e.name,s.transforms,s.nodeAttributes),this.programs.compute.set(s.computeShader,a),n.createProgram(a));const o=this._getComputeCacheKey(e,a);let l=this.caches.get(o);void 0===l&&(r&&0===r.usedTimes&&this._releasePipeline(r),l=this._getComputePipeline(e,a,o,t)),l.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=l}return i.pipeline}getForRender(e,t=null){const{backend:n}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const s=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(s.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new xM(s.vertexShader,"vertex",a),this.programs.vertex.set(s.vertexShader,o),n.createProgram(o));let l=this.programs.fragment.get(s.fragmentShader);void 0===l&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),l=new xM(s.fragmentShader,"fragment",a),this.programs.fragment.set(s.fragmentShader,l),n.createProgram(l));const u=this._getRenderCacheKey(e,o,l);let c=this.caches.get(u);void 0===c?(r&&0===r.usedTimes&&this._releasePipeline(r),c=this._getRenderPipeline(e,o,l,u,t)):e.pipeline=c,c.usedTimes++,o.usedTimes++,l.usedTimes++,i.pipeline=c}return i.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,n,i){n=n||this._getComputeCacheKey(e,t);let r=this.caches.get(n);return void 0===r&&(r=new vM(n,t),this.caches.set(n,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,n,i,r){i=i||this._getRenderCacheKey(e,t,n);let s=this.caches.get(i);return void 0===s&&(s=new _M(i,t,n),this.caches.set(i,s),e.pipeline=s,this.backend.createRenderPipeline(e,r)),s}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,n=e.stage;this.programs[n].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class SM extends sM{constructor(e,t,n,i,r,s){super(),this.backend=e,this.textures=n,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=s,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?uM:lM;this.attributes.update(e,n)}}_update(e,t){const{backend:n}=this;let i=!1,r=!0,s=0,a=0;for(const t of e.bindings){if(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?uM:lM;this.attributes.update(e,n)}if(t.isUniformBuffer){t.update()&&n.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){const e=this.textures.get(t.texture);t.needsBindingsUpdate(e.generation)&&(i=!0);const o=t.update(),l=t.texture;o&&this.textures.updateTexture(l);const u=n.get(l);if(void 0!==u.externalTexture||e.isDefaultTexture?r=!1:(s=10*s+l.id,a+=l.version),!0===n.isWebGPUBackend&&void 0===u.texture&&void 0===u.externalTexture&&(console.error("Bindings._update: binding should be available:",t,o,l,t.textureNode.value,i),this.textures.updateTexture(l),i=!0),!0===l.isStorageTexture){const e=this.get(l);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(l)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(l),e.needsMipmap=!1)}}}!0===i&&this.backend.updateBindings(e,t,r?s:0,a)}}function TM(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function MM(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function EM(e){return(e.transmission>0||e.transmissionNode)&&2===e.side&&!1===e.forceSinglePass}class wM{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,n),this.lightsArray=[],this.scene=t,this.camera=n,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,n,i,r,s,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:n,groupOrder:i,renderOrder:e.renderOrder,z:r,group:s,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=n,o.groupOrder=i,o.renderOrder=e.renderOrder,o.z=r,o.group=s,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,n,i,r,s,a){const o=this.getNextRenderItem(e,t,n,i,r,s,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===n.transparent||n.transmission>0?(EM(n)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,n,i,r,s,a){const o=this.getNextRenderItem(e,t,n,i,r,s,a);!0===n.transparent||n.transmission>0?(EM(n)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||TM),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||MM),this.transparent.length>1&&this.transparent.sort(t||MM)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,l=a.height>>t;let u=e.depthTexture||r[t];const c=!0===e.depthBuffer||!0===e.stencilBuffer;let h=!1;void 0===u&&c&&(u=new rs,u.format=e.stencilBuffer?xe:ye,u.type=e.stencilBuffer?de:oe,u.image.width=o,u.image.height=l,r[t]=u),n.width===a.width&&a.height===n.height||(h=!0,u&&(u.needsUpdate=!0,u.image.width=o,u.image.height=l)),n.width=a.width,n.height=a.height,n.textures=s,n.depthTexture=u||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==i&&(h=!0,u&&(u.needsUpdate=!0),n.sampleCount=i);const d={sampleCount:i};if(!0!==e.isXRRenderTarget){for(let e=0;e{e.removeEventListener("dispose",t);for(let e=0;e0){const i=e.image;if(void 0===i)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const n=[];for(const t of e.images)n.push(t);t.images=n}else t.image=i;void 0!==n.isDefaultTexture&&!0!==n.isDefaultTexture||(r.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&r.generateMipmaps(e)}}else r.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version}if(!0!==n.initialized){n.initialized=!0,n.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e),this.info.memory.textures--};e.addEventListener("dispose",t)}n.version=e.version}getSize(e,t=OM){let n=e.images?e.images[0]:e.image;return n?(void 0!==n.image&&(n=n.image),t.width=n.width||1,t.height=n.height||1,t.depth=e.isCubeTexture?6:n.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let i;return i=e.isCompressedTexture?e.mipmaps?e.mipmaps.length:1:Math.floor(Math.log2(Math.max(t,n)))+1,i}needsMipmaps(e){return this.isEnvironmentTexture(e)||!0===e.isCompressedTexture||e.generateMipmaps}isEnvironmentTexture(e){const t=e.mapping;return t===j||t===W||t===V||t===H}_destroyTexture(e){this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e)}}class BM extends Pi{constructor(e,t,n,i=1){super(e,t,n),this.a=i}set(e,t,n,i=1){return this.a=i,super.set(e,t,n)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class kM extends Nm{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class zM extends sf{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const n=new Wf(t);return this._currentCond=L_(e,n),this.add(this._currentCond)}ElseIf(e,t){const n=new Wf(t),i=L_(e,n);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new Wf(e),this}build(e,...t){const n=Jf();Qf(this);for(const t of this.nodes)t.build(e,"void");return Qf(n),this.outputNode?this.outputNode.build(e,...t):super.build(e,...t)}else(...e){return console.warn("TSL.StackNode: .else() has been renamed to .Else()."),this.Else(...e)}elseif(...e){return console.warn("TSL.StackNode: .elseif() has been renamed to .ElseIf()."),this.ElseIf(...e)}}const GM=Yf(zM);new Hr,new un,new un,new un,new kn,new un(0,0,-1),new nn,new un,new un,new nn,new It;const VM=new rn;Yx.flipX(),VM.depthTexture=new rs(1,1);const HM=new Qs(-1,1,1,-1,0,1);class jM extends tr{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new qi([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new qi(t,2))}}const WM=new jM;class XM extends pr{constructor(e=null){super(WM,e),this.camera=HM,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,HM)}render(e){e.render(this,HM)}}const qM=new Yn,$M=new kn;class YM extends sf{static get type(){return"SceneNode"}constructor(e=YM.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,n=null!==this.scene?this.scene:e.scene;let i;return t===YM.BACKGROUND_BLURRINESS?i=xy("backgroundBlurriness","float",n):t===YM.BACKGROUND_INTENSITY?i=xy("backgroundIntensity","float",n):t===YM.BACKGROUND_ROTATION?i=Cm("mat4").label("backgroundRotation").setGroup(wm).onRenderUpdate((()=>{const e=n.background;return null!==e&&e.isTexture&&300!==e.mapping?(qM.copy(n.backgroundRotation),qM.x*=-1,qM.y*=-1,qM.z*=-1,$M.makeRotationFromEuler(qM)):$M.identity(),$M})):console.error("THREE.SceneNode: Unknown scope:",t),i}}YM.BACKGROUND_BLURRINESS="backgroundBlurriness",YM.BACKGROUND_INTENSITY="backgroundIntensity",YM.BACKGROUND_ROTATION="backgroundRotation";const KM=Kf(YM,YM.BACKGROUND_BLURRINESS),ZM=Kf(YM,YM.BACKGROUND_INTENSITY),QM=Kf(YM,YM.BACKGROUND_ROTATION);Zf((({texture:e,uv:t})=>{const n=1e-4,i=cm().toVar();return em(t.x.lessThan(n),(()=>{i.assign(cm(1,0,0))})).ElseIf(t.y.lessThan(n),(()=>{i.assign(cm(0,1,0))})).ElseIf(t.z.lessThan(n),(()=>{i.assign(cm(0,0,1))})).ElseIf(t.x.greaterThan(.9999),(()=>{i.assign(cm(-1,0,0))})).ElseIf(t.y.greaterThan(.9999),(()=>{i.assign(cm(0,-1,0))})).ElseIf(t.z.greaterThan(.9999),(()=>{i.assign(cm(0,0,-1))})).Else((()=>{const n=.01,r=e.sample(t.add(cm(-.01,0,0))).r.sub(e.sample(t.add(cm(n,0,0))).r),s=e.sample(t.add(cm(0,-.01,0))).r.sub(e.sample(t.add(cm(0,n,0))).r),a=e.sample(t.add(cm(0,0,-.01))).r.sub(e.sample(t.add(cm(0,0,n))).r);i.assign(cm(r,s,a))})),i.normalize()}));const JM=new It;class eE extends xv{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class tE extends eE{static get type(){return"PassMultipleTextureNode"}constructor(e,t,n=!1){super(e,null),this.textureName=t,this.previousTexture=n}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){return new this.constructor(this.passNode,this.textureName,this.previousTexture)}}class nE extends lf{static get type(){return"PassNode"}constructor(e,t,n,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new rs;r.isRenderTargetTexture=!0,r.name="depth";const s=new rn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ue,...i});s.texture.name="output",s.depthTexture=r,this.renderTarget=s,this._textures={output:s.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Cm(0),this._cameraFar=Cm(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=$p}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}isGlobal(){return!0}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const n=this._textures[e],i=this.renderTarget.textures.indexOf(n);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=n,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=Xf(new tE(this,e)),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=Xf(new tE(this,e,!0)),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const n=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=lb(this.getTextureNode(e),n,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const n=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=ab(r,n,i)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,!0===e.backend.isWebGLBackend&&(this.renderTarget.samples=0),this.renderTarget.texture.type=e.getColorBufferType(),this.scope===nE.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:n}=this;let i,r;const s=t.getOutputRenderTarget();s&&!0===s.isXRRenderTarget?(r=1,i=t.xr.getCamera(),t.xr.updateCamera(i),JM.set(s.width,s.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(JM)),this._pixelRatio=r,this.setSize(JM.width,JM.height);const a=t.getRenderTarget(),o=t.getMRT(),l=i.layers.mask;this._cameraNear.value=i.near,this._cameraFar.value=i.far,null!==this._layers&&(i.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(n,i),t.setRenderTarget(a),t.setMRT(o),i.layers.mask=l}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio*this._resolution,i=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(n,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}nE.COLOR="color",nE.DEPTH="depth";const iE=Zf((([e,t])=>e.mul(t).clamp())).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),rE=Zf((([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp())).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),sE=Zf((([e,t])=>{const n=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return n.div(i).pow(2.2)})).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),aE=Zf((([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),n=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(n)})),oE=Zf((([e,t])=>{const n=ym(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=ym(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=aE(e),(e=i.mul(e)).clamp()})).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),lE=ym(cm(1.6605,-.1246,-.0182),cm(-.5876,1.1329,-.1006),cm(-.0728,-.0083,1.1187)),uE=ym(cm(.6274,.0691,.0164),cm(.3293,.9195,.088),cm(.0433,.0113,.8956)),cE=Zf((([e])=>{const t=cm(e).toVar(),n=cm(t.mul(t)).toVar(),i=cm(n.mul(n)).toVar();return nm(15.5).mul(i.mul(n)).sub(hg(40.14,i.mul(t))).add(hg(31.96,i).sub(hg(6.868,n.mul(t))).add(hg(.4298,n).add(hg(.1191,t).sub(.00232))))})),hE=Zf((([e,t])=>{const n=cm(e).toVar(),i=ym(cm(.856627153315983,.137318972929847,.11189821299995),cm(.0951212405381588,.761241990602591,.0767994186031903),cm(.0482516061458583,.101439036467562,.811302368396859)),r=ym(cm(1.1271005818144368,-.1413297634984383,-.14132976349843826),cm(-.11060664309660323,1.157823702216272,-.11060664309660294),cm(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=nm(-12.47393),a=nm(4.026069);return n.mulAssign(t),n.assign(uE.mul(n)),n.assign(i.mul(n)),n.assign(p_(n,1e-10)),n.assign(zg(n)),n.assign(n.sub(s).div(a.sub(s))),n.assign(R_(n,0,1)),n.assign(cE(n)),n.assign(r.mul(n)),n.assign(b_(p_(cm(0),n),cm(2.2))),n.assign(lE.mul(n)),n.assign(R_(n,0,1)),n})).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),dE=Zf((([e,t])=>{const n=nm(.76),i=nm(.15);e=e.mul(t);const r=d_(e.r,d_(e.g,e.b)),s=L_(r.lessThan(.08),r.sub(hg(6.25,r.mul(r))),.04);e.subAssign(s);const a=p_(e.r,p_(e.g,e.b));em(a.lessThan(n),(()=>e));const o=cg(1,n),l=cg(1,o.mul(o).div(a.add(o.sub(n))));e.mulAssign(l.div(a));const u=cg(1,dg(1,i.mul(a.sub(l)).add(1)));return A_(e,cm(l),u)})).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class pE extends sf{static get type(){return"CodeNode"}constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.code=e,this.includes=t,this.language=n}isGlobal(){return!0}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const n of t)n.build(e);const n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}class fE extends pE{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let n=t.nodeFunction;return void 0===n&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),i=n.name,r=n.type,s=e.getCodeFromNode(this,r);""!==i&&(s.name=i);const a=e.getPropertyName(s),o=this.getNodeFunction(e).getCode(a);return s.code=o+"\n","property"===t?a:e.format(`${a}()`,r,t)}}function mE(e){let t;const n=e.context.getViewZ;return void 0!==n&&(t=n(this)),(t||qv.z).negate()}const gE=Zf((([e,t],n)=>{const i=mE(n);return N_(e,t,i)})),_E=Zf((([e],t)=>{const n=mE(t);return e.mul(e,n,n).negate().exp().oneMinus()})),vE=Zf((([e,t])=>fm(t.toFloat().mix(Zm.rgb,e.toVec3()),Zm.a)));Yf(class extends sf{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:n}=e;!0===n.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class yE extends lf{static get type(){return"AtomicFunctionNode"}constructor(e,t,n,i=null){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=n,this.storeNode=i}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=this.method,n=this.getNodeType(e),i=this.getInputType(e),r=this.pointerNode,s=this.valueNode,a=[];a.push(`&${r.build(e,i)}`),null!==s&&a.push(s.build(e,i));const o=`${e.getMethod(t,n)}( ${a.join(", ")} )`;if(null!==this.storeNode){const t=this.storeNode.build(e,i);e.addLineFlowCode(`${t} = ${o}`,this)}else e.addLineFlowCode(o,this)}}let xE;function bE(e){xE=xE||new WeakMap;let t=xE.get(e);return void 0===t&&xE.set(e,t={}),t}function SE(e){const t=bE(e);return t.shadowMatrix||(t.shadowMatrix=Cm("mat4").setGroup(wm).onRenderUpdate((()=>(!0!==e.castShadow&&e.shadow.updateMatrices(e),e.shadow.matrix))))}function TE(e){const t=bE(e);return t.position||(t.position=Cm(new un).setGroup(wm).onRenderUpdate(((t,n)=>n.value.setFromMatrixPosition(e.matrixWorld))))}function ME(e){const t=bE(e);return t.viewPosition||(t.viewPosition=Cm(new un).setGroup(wm).onRenderUpdate((({camera:t},n)=>{n.value=n.value||new un,n.value.setFromMatrixPosition(e.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)})))}yE.ATOMIC_LOAD="atomicLoad",yE.ATOMIC_STORE="atomicStore",yE.ATOMIC_ADD="atomicAdd",yE.ATOMIC_SUB="atomicSub",yE.ATOMIC_MAX="atomicMax",yE.ATOMIC_MIN="atomicMin",yE.ATOMIC_AND="atomicAnd",yE.ATOMIC_OR="atomicOr",yE.ATOMIC_XOR="atomicXor",Yf(yE);const EE=e=>Dv.transformDirection(TE(e).sub(function(e){const t=bE(e);return t.targetPosition||(t.targetPosition=Cm(new un).setGroup(wm).onRenderUpdate(((t,n)=>n.value.setFromMatrixPosition(e.target.matrixWorld))))}(e))),wE=(e,t)=>{for(const n of t)if(n.isAnalyticLightNode&&n.light.id===e)return n;return null},AE=new WeakMap;class RE extends sf{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=cm().toVar("totalDiffuse"),this.totalSpecularNode=cm().toVar("totalSpecular"),this.outgoingLightNode=cm().toVar("outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=[],t=this._lights;for(let n=0;ne.sort(((e,t)=>e.id-t.id)))(this._lights),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(Xf(e));else{let i=null;if(null!==n&&(i=wE(e.id,n)),null===i){const n=r.getLightNodeClass(e.constructor);if(null===n){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;AE.has(e)?i=AE.get(e):(i=Xf(new n(e)),AE.set(e,i)),t.push(i)}}this._lightNodes=t}setupDirectLight(e,t,n){const{lightingModel:i,reflectedLight:r}=e.context;i.direct({...n,lightNode:t,reflectedLight:r},e)}setupDirectRectAreaLight(e,t,n){const{lightingModel:i,reflectedLight:r}=e.context;i.directRectArea({...n,lightNode:t,reflectedLight:r},e)}setupLights(e,t){for(const n of t)n.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode;const i=e.context,r=i.lightingModel,s=e.getDataFromNode(this);if(r){const{totalDiffuseNode:t,totalSpecularNode:a}=this;i.outgoingLight=n;const o=e.addStack();s.nodes=o.nodes,r.start(e);const{backdrop:l,backdropAlpha:u}=i,{directDiffuse:c,directSpecular:h,indirectDiffuse:d,indirectSpecular:p}=i.reflectedLight;let f=c.add(d);null!==l&&(f=cm(null!==u?u.mix(f,l):l),i.material.transparent=!0),t.assign(f),a.assign(h.add(p)),n.assign(t.add(a)),r.finish(e),n=n.bypass(e.removeStack())}else s.nodes=[];return e.lightsNode=t,n}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class CE extends sf{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Yp,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){NE.assign(t.shadowPositionNode||e.shadowPositionWorld||Wv)}dispose(){this.updateBeforeType=qp}}const NE=Pm("vec3","shadowPositionWorld");function PE(e,t){return t=function(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new Pi),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}const DE=new WeakMap,UE=Zf((([e,t,n])=>{let i=Wv.sub(e).length();return i=i.sub(t).div(n.sub(t)),i=i.saturate(),i})),LE=e=>{let t=DE.get(e);if(void 0===t){const n=e.isPointLight?(e=>{const t=e.shadow.camera,n=xy("near","float",t).setGroup(wm),i=xy("far","float",t).setGroup(wm),r=Ov(e);return UE(r,n,i)})(e):null;t=new _b,t.colorNode=fm(0,0,0,1),t.depthNode=n,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,DE.set(e,t)}return t},IE=Zf((({depthTexture:e,shadowCoord:t})=>bv(e,t.xy).compare(t.z))),OE=Zf((({depthTexture:e,shadowCoord:t,shadow:n})=>{const i=(t,n)=>bv(e,t).compare(n),r=xy("mapSize","vec2",n).setGroup(wm),s=xy("radius","float",n).setGroup(wm),a=am(1).div(r),o=a.x.negate().mul(s),l=a.y.negate().mul(s),u=a.x.mul(s),c=a.y.mul(s),h=o.div(2),d=l.div(2),p=u.div(2),f=c.div(2);return ug(i(t.xy.add(am(o,l)),t.z),i(t.xy.add(am(0,l)),t.z),i(t.xy.add(am(u,l)),t.z),i(t.xy.add(am(h,d)),t.z),i(t.xy.add(am(0,d)),t.z),i(t.xy.add(am(p,d)),t.z),i(t.xy.add(am(o,0)),t.z),i(t.xy.add(am(h,0)),t.z),i(t.xy,t.z),i(t.xy.add(am(p,0)),t.z),i(t.xy.add(am(u,0)),t.z),i(t.xy.add(am(h,f)),t.z),i(t.xy.add(am(0,f)),t.z),i(t.xy.add(am(p,f)),t.z),i(t.xy.add(am(o,c)),t.z),i(t.xy.add(am(0,c)),t.z),i(t.xy.add(am(u,c)),t.z)).mul(1/17)})),FE=Zf((({depthTexture:e,shadowCoord:t,shadow:n})=>{const i=(t,n)=>bv(e,t).compare(n),r=xy("mapSize","vec2",n).setGroup(wm),s=am(1).div(r),a=s.x,o=s.y,l=t.xy,u=Xg(l.mul(r).add(.5));return l.subAssign(u.mul(s)),ug(i(l,t.z),i(l.add(am(a,0)),t.z),i(l.add(am(0,o)),t.z),i(l.add(s),t.z),A_(i(l.add(am(a.negate(),0)),t.z),i(l.add(am(a.mul(2),0)),t.z),u.x),A_(i(l.add(am(a.negate(),o)),t.z),i(l.add(am(a.mul(2),o)),t.z),u.x),A_(i(l.add(am(0,o.negate())),t.z),i(l.add(am(0,o.mul(2))),t.z),u.y),A_(i(l.add(am(a,o.negate())),t.z),i(l.add(am(a,o.mul(2))),t.z),u.y),A_(A_(i(l.add(am(a.negate(),o.negate())),t.z),i(l.add(am(a.mul(2),o.negate())),t.z),u.x),A_(i(l.add(am(a.negate(),o.mul(2))),t.z),i(l.add(am(a.mul(2),o.mul(2))),t.z),u.x),u.y)).mul(1/9)})),BE=Zf((({depthTexture:e,shadowCoord:t})=>{const n=nm(1).toVar(),i=bv(e).sample(t.xy).rg,r=m_(t.z,i.x);return em(r.notEqual(nm(1)),(()=>{const e=t.z.sub(i.x),s=p_(0,i.y.mul(i.y));let a=s.div(s.add(e.mul(e)));a=R_(cg(a,.3).div(.95-.3)),n.assign(R_(p_(r,a)))})),n})),kE=Zf((({samples:e,radius:t,size:n,shadowPass:i})=>{const r=nm(0).toVar(),s=nm(0).toVar(),a=e.lessThanEqual(nm(1)).select(nm(0),nm(2).div(e.sub(1))),o=e.lessThanEqual(nm(1)).select(nm(0),nm(-1));Ix({start:im(0),end:im(e),type:"int",condition:"<"},(({i:e})=>{const l=o.add(nm(e).mul(a)),u=i.sample(ug(Zx.xy,am(0,l).mul(t)).div(n)).x;r.addAssign(u),s.addAssign(u.mul(u))})),r.divAssign(e),s.divAssign(e);const l=Gg(s.sub(r.mul(r)));return am(r,l)})),zE=Zf((({samples:e,radius:t,size:n,shadowPass:i})=>{const r=nm(0).toVar(),s=nm(0).toVar(),a=e.lessThanEqual(nm(1)).select(nm(0),nm(2).div(e.sub(1))),o=e.lessThanEqual(nm(1)).select(nm(0),nm(-1));Ix({start:im(0),end:im(e),type:"int",condition:"<"},(({i:e})=>{const l=o.add(nm(e).mul(a)),u=i.sample(ug(Zx.xy,am(l,0).mul(t)).div(n));r.addAssign(u.x),s.addAssign(ug(u.y.mul(u.y),u.x.mul(u.x)))})),r.divAssign(e),s.divAssign(e);const l=Gg(s.sub(r.mul(r)));return am(r,l)})),GE=[IE,OE,FE,BE];let VE;const HE=new XM;class jE extends CE{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:r}){const s=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),a=t({depthTexture:n,shadowCoord:i,shadow:r});return s.select(a,nm(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:i}=e,r=xy("bias","float",n).setGroup(wm);let s,a=t;if(n.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)a=a.xyz.div(a.w),s=a.z,i.coordinateSystem===St&&(s=s.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=xy("near","float",n.camera).setGroup(wm),i=xy("far","float",n.camera).setGroup(wm);s=ub(e.negate(),t,i)}return a=cm(a.x,a.y.oneMinus(),s.add(r)),a}getShadowFilterFn(e){return GE[e]}setupShadow(e){const{renderer:t}=e,{light:n,shadow:i}=this,r=t.shadowMap.type,s=new rs(i.mapSize.width,i.mapSize.height);s.compareFunction=ht;const a=e.createRenderTarget(i.mapSize.width,i.mapSize.height);if(a.depthTexture=s,i.camera.updateProjectionMatrix(),3===r){s.compareFunction=null,this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:Te,type:ue}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:Te,type:ue});const t=bv(s),n=bv(this.vsmShadowMapVertical.texture),r=xy("blurSamples","float",i).setGroup(wm),a=xy("radius","float",i).setGroup(wm),o=xy("mapSize","vec2",i).setGroup(wm);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new _b);l.fragmentNode=kE({samples:r,radius:a,size:o,shadowPass:t}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new _b),l.fragmentNode=zE({samples:r,radius:a,size:o,shadowPass:n}).context(e.getSharedContext()),l.name="VSMHorizontal"}const o=xy("intensity","float",i).setGroup(wm),l=xy("normalBias","float",i).setGroup(wm),u=SE(n).mul(NE.add(iy.mul(l))),c=this.setupShadowCoord(e,u),h=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===h)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const d=3===r?this.vsmShadowMapHorizontal.texture:s,p=this.setupShadowFilter(e,{filterFn:h,shadowTexture:a.texture,depthTexture:d,shadowCoord:c,shadow:i}),f=bv(a.texture,c),m=A_(1,p.rgb.mix(f,1),o.mul(f.a)).toVar();return this.shadowMap=a,this.shadow.map=a,m}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Zf((()=>{let t=this._node;return this.setupShadowPosition(e),null===t&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t}))()}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:r,scene:s}=e;t.updateMatrices(i),n.setSize(t.mapSize.width,t.mapSize.height),r.render(s,t.camera)}updateShadow(e){const{shadowMap:t,light:n,shadow:i}=this,{renderer:r,scene:s,camera:a}=e,o=r.shadowMap.type,l=t.depthTexture.version;this._depthVersionCached=l,i.camera.layers.mask=a.layers.mask;const u=r.getRenderObjectFunction(),c=r.getMRT(),h=!!c&&c.has("velocity");VE=function(e,t,n){return n=function(e,t){return t=function(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}(t,n=PE(e,n)),n}(r,s,VE),s.overrideMaterial=LE(n),r.setRenderObjectFunction(((e,t,n,s,l,u,...c)=>{(!0===e.castShadow||e.receiveShadow&&3===o)&&(h&&(Wp(e).useVelocity=!0),e.onBeforeShadow(r,e,a,i.camera,s,t.overrideMaterial,u),r.renderObject(e,t,n,s,l,u,...c),e.onAfterShadow(r,e,a,i.camera,s,t.overrideMaterial,u))})),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(u),!0!==n.isPointLight&&3===o&&this.vsmPass(r),function(e,t,n){!function(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}(e,n),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,n)}(r,s,VE)}vsmPass(e){const{shadow:t}=this;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height),e.setRenderTarget(this.vsmShadowMapVertical),HE.material=this.vsmMaterialVertical,HE.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),HE.material=this.vsmMaterialHorizontal,HE.render(e)}dispose(){this.shadowMap.dispose(),this.shadowMap=null,null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null),super.dispose()}updateBefore(e){const{shadow:t}=this;let n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId[e.camera]===e.frameId&&(n=!1),this._cameraFrameId[e.camera]=e.frameId),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const WE=new Pi,XE=Zf((([e,t])=>{const n=e.toVar(),i=Jg(n),r=dg(1,p_(i.x,p_(i.y,i.z)));i.mulAssign(r),n.mulAssign(r.mul(t.mul(2).oneMinus()));const s=am(n.xy).toVar(),a=t.mul(1.5).oneMinus();return em(i.z.greaterThanEqual(a),(()=>{em(n.z.greaterThan(0),(()=>{s.x.assign(cg(4,n.x))}))})).ElseIf(i.x.greaterThanEqual(a),(()=>{const e=e_(n.x);s.x.assign(n.z.mul(e).add(e.mul(2)))})).ElseIf(i.y.greaterThanEqual(a),(()=>{const e=e_(n.y);s.x.assign(n.x.add(e.mul(2)).add(2)),s.y.assign(n.z.mul(e).sub(2))})),am(.125,.25).mul(s).add(am(.375,.75)).flipY()})).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),qE=Zf((({depthTexture:e,bd3D:t,dp:n,texelSize:i})=>bv(e,XE(t,i.y)).compare(n))),$E=Zf((({depthTexture:e,bd3D:t,dp:n,texelSize:i,shadow:r})=>{const s=xy("radius","float",r).setGroup(wm),a=am(-1,1).mul(s).mul(i.y);return bv(e,XE(t.add(a.xyy),i.y)).compare(n).add(bv(e,XE(t.add(a.yyy),i.y)).compare(n)).add(bv(e,XE(t.add(a.xyx),i.y)).compare(n)).add(bv(e,XE(t.add(a.yyx),i.y)).compare(n)).add(bv(e,XE(t,i.y)).compare(n)).add(bv(e,XE(t.add(a.xxy),i.y)).compare(n)).add(bv(e,XE(t.add(a.yxy),i.y)).compare(n)).add(bv(e,XE(t.add(a.xxx),i.y)).compare(n)).add(bv(e,XE(t.add(a.yxx),i.y)).compare(n)).mul(1/9)})),YE=Zf((({filterFn:e,depthTexture:t,shadowCoord:n,shadow:i})=>{const r=n.xyz.toVar(),s=r.length(),a=Cm("float").setGroup(wm).onRenderUpdate((()=>i.camera.near)),o=Cm("float").setGroup(wm).onRenderUpdate((()=>i.camera.far)),l=xy("bias","float",i).setGroup(wm),u=Cm(i.mapSize).setGroup(wm),c=nm(1).toVar();return em(s.sub(o).lessThanEqual(0).and(s.sub(a).greaterThanEqual(0)),(()=>{const n=s.sub(a).div(o.sub(a)).toVar();n.addAssign(l);const h=r.normalize(),d=am(1).div(u.mul(am(4,2)));c.assign(e({depthTexture:t,bd3D:h,dp:n,texelSize:d,shadow:i}))})),c})),KE=new nn,ZE=new It,QE=new It;class JE extends jE{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?qE:$E}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:n,depthTexture:i,shadowCoord:r,shadow:s}){return YE({filterFn:t,shadowTexture:n,depthTexture:i,shadowCoord:r,shadow:s})}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:r,scene:s}=e,a=t.getFrameExtents();QE.copy(t.mapSize),QE.multiply(a),n.setSize(QE.width,QE.height),ZE.copy(t.mapSize);const o=r.autoClear,l=r.getClearColor(WE),u=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha),r.clear();const c=t.getViewportCount();for(let e=0;eXf(new jE(e,t)))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let n=this.shadowColorNode;if(null===n){const t=this.light.shadow.shadowNode;let i;i=void 0!==t?Xf(t):this.setupShadowNode(e),this.shadowNode=i,this.shadowColorNode=n=this.colorNode.mul(i),this.baseColorNode=this.colorNode}this.colorNode=n}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const tw=Zf((({lightDistance:e,cutoffDistance:t,decayExponent:n})=>{const i=e.pow(n).max(.01).reciprocal();return t.greaterThan(0).select(i.mul(e.div(t).pow4().oneMinus().clamp().pow2()),i)}));class nw extends ew{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Cm(0).setGroup(wm),this.decayExponentNode=Cm(2).setGroup(wm)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>Xf(new JE(e,t)))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:n,decayExponent:i})=>{const r=t.normalize(),s=t.length(),a=tw({lightDistance:s,cutoffDistance:n,decayExponent:i});return{lightDirection:r,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}Zf((([e=mv()],{renderer:t,material:n})=>{const i=nm(1).toVar(),r=w_(e.mul(2).sub(1));if(n.alphaToCoverage&&t.samples>1){const e=nm(r.fwidth()).toVar();i.assign(N_(e.oneMinus(),e.add(1),r).oneMinus())}else r.greaterThan(1).discard();return i}));const iw=Zf((([e,t])=>{const n=e.x,i=e.y,r=e.z;let s=t.element(0).mul(.886227);return s=s.add(t.element(1).mul(1.023328).mul(i)),s=s.add(t.element(2).mul(1.023328).mul(r)),s=s.add(t.element(3).mul(1.023328).mul(n)),s=s.add(t.element(4).mul(.858086).mul(n).mul(i)),s=s.add(t.element(5).mul(.858086).mul(i).mul(r)),s=s.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),s=s.add(t.element(7).mul(.858086).mul(n).mul(r)),s=s.add(t.element(8).mul(.429043).mul(hg(n,n).sub(hg(i,i)))),s})),rw=new BM;class sw extends sM{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let s=!1;if(null===r)i._clearColor.getRGB(rw),rw.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(rw),rw.a=1,s=!0;else if(!0===r.isNode){const n=this.get(e),s=r;rw.copy(i._clearColor);let a=n.backgroundMesh;if(void 0===a){const e=O_(fm(s).mul(ZM),{getUV:()=>QM.mul(ty),getTextureLevel:()=>KM});let t=Sx;t=t.setZ(t.w);const i=new _b;i.name="Background.material",i.side=1,i.depthTest=!1,i.depthWrite=!1,i.fog=!1,i.lights=!1,i.vertexNode=t,i.colorNode=e,n.backgroundMeshNode=e,n.backgroundMesh=a=new pr(new bs(1,32,32),i),a.frustumCulled=!1,a.name="Background.mesh",a.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)}}const o=s.getCacheKey();n.backgroundCacheKey!==o&&(n.backgroundMeshNode.node=fm(s).mul(ZM),n.backgroundMeshNode.needsUpdate=!0,a.material.needsUpdate=!0,n.backgroundCacheKey=o),t.unshift(a,a.geometry,a.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",r);const a=i.xr.getEnvironmentBlendMode();if("additive"===a?rw.set(0,0,0,1):"alpha-blend"===a&&rw.set(0,0,0,0),!0===i.autoClear||!0===s){const e=n.clearColorValue;e.r=rw.r,e.g=rw.g,e.b=rw.b,e.a=rw.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(e.r*=e.a,e.g*=e.a,e.b*=e.a),n.depthClearValue=i._clearDepth,n.stencilClearValue=i._clearStencil,n.clearColor=!0===i.autoClearColor,n.clearDepth=!0===i.autoClearDepth,n.clearStencil=!0===i.autoClearStencil}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}let aw=0;class ow{constructor(e="",t=[],n=0,i=[]){this.name=e,this.bindings=t,this.index=n,this.bindingsReference=i,this.id=aw++}}class lw{constructor(e,t,n,i,r,s,a,o,l,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=u,this.nodeAttributes=i,this.bindings=r,this.updateNodes=s,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=l,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const n=new ow(t.name,[],t.index,t);e.push(n);for(const e of t.bindings)n.bindings.push(e.clone())}else e.push(t)}return e}}class uw{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class cw{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n.getSelf()}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class hw{constructor(e,t,n=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=i}}class dw extends hw{constructor(e,t){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0}}class pw{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let fw=0;class mw{constructor(e=null){this.id=fw++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return void 0===t&&null!==this.parent&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class gw{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class _w{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class vw extends _w{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class yw extends _w{constructor(e,t=new It){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class xw extends _w{constructor(e,t=new un){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class bw extends _w{constructor(e,t=new nn){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class Sw extends _w{constructor(e,t=new Pi){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class Tw extends _w{constructor(e,t=new fa){super(e,t),this.isMatrix2Uniform=!0,this.boundary=16,this.itemSize=4}}class Mw extends _w{constructor(e,t=new Ot){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class Ew extends _w{constructor(e,t=new kn){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class ww extends vw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Aw extends yw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Rw extends xw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Cw extends bw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Nw extends Sw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Pw extends Tw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Dw extends Mw{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Uw extends Ew{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const Lw=new WeakMap,Iw=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),Ow=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class Fw{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=n,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.flow={code:""},this.chaining=[],this.stack=GM(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new mw,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.useComparisonMethod=!1}getBindGroupsCache(){let e=Lw.get(this.renderer);return void 0===e&&(e=new eM,Lw.set(this.renderer,e)),e}createRenderTarget(e,t,n){return new rn(e,t,n)}createCubeRenderTarget(e,t){return new wb(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const n=this.getBindGroupsCache(),i=[];let r,s=!0;for(const e of t)i.push(e),s=s&&!0!==e.groupNode.shared;return s?(r=n.get(i),void 0===r&&(r=new ow(e,i,this.bindingsIndexes[e].group,i),n.set(i,r))):r=new ow(e,i,this.bindingsIndexes[e].group,i),r}getBindGroupArray(e,t){const n=this.bindings[t];let i=n[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},n=this.bindings;for(const e of tf)for(const i in n[e]){const r=n[e][i];(t[i]||(t[i]=[])).push(...r)}e=[];for(const n in t){const i=t[n],r=this._getBindGroup(n,i);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort(((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order));for(let t=0;t=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${Ow(t.r)}, ${Ow(t.g)}, ${Ow(t.b)} )`;const n=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===n)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===n&&"mat2"!==e)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(n>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const n=this.attributes;for(const t of n)if(t.name===e)return t;const i=new uw(e,t);return n.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===ae)return"int";if(t===oe)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let n=function(e){return Gp.get(e)}(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(n=n.replace("vec","mat")),i+n}getTypeFromArray(e){return Iw.get(e.constructor)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const n=t.array,i=e.itemSize,r=e.normalized;let s;return e instanceof Xi||!0===r||(s=this.getTypeFromArray(n)),this.getTypeFromLength(i,s)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return null!==n?Number(n[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}addStack(){return this.stack=GM(this.stack),this.stacks.push(Jf()||this.stack),Qf(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,Qf(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){let i=(n=null===n?e.isGlobal(this)?this.globalCache:this.cache:n).getData(e);return void 0===i&&(i={},n.setData(e,i)),void 0===i[t]&&(i[t]={}),i[t]}getNodeProperties(e,t="any"){const n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const n=this.getDataFromNode(e);let i=n.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new uw("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),n.bufferAttribute=i}return i}getStructTypeFromNode(e,t,n=null,i=this.shaderStage){const r=this.getDataFromNode(e,i,this.globalCache);let s=r.structType;if(void 0===s){const e=this.structs.index++;null===n&&(n="StructType"+e),s=new gw(n,t),this.structs[i].push(s),r.structType=s}return s}getOutputStructTypeFromNode(e,t){const n=this.getStructTypeFromNode(e,t,"OutputType","fragment");return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,i=null){const r=this.getDataFromNode(e,n,this.globalCache);let s=r.uniform;if(void 0===s){const a=this.uniforms.index++;s=new cw(i||"nodeUniform"+a,t,e),this.uniforms[n].push(s),r.uniform=s}return s}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,n=e.getNodeType(this),i=this.shaderStage,r=!1){const s=this.getDataFromNode(e,i);let a=s.variable;if(void 0===a){const o=r?"_const":"_var",l=this.vars[i]||(this.vars[i]=[]),u=this.vars[o]||(this.vars[o]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+u,this.vars[o]++);const c=this.getArrayCount(e);a=new hw(t,n,r,c),r||l.push(a),s.variable=a}return a}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,n=e.getNodeType(this)){const i=this.getDataFromNode(e,"any");let r=i.varying;if(void 0===r){const e=this.varyings,s=e.length;null===t&&(t="nodeVarying"+s),r=new dw(t,n),e.push(r),i.varying=r}return r}getCodeFromNode(e,t,n=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[n]||(this.codes[n]=[]),s=e.length;r=new pw("nodeCode"+s,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:n,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,s=t;for(;s;){if(!0===i.get(s)){r=!1;break}s=this.getDataFromNode(s).parentNodeBlock}if(r)for(const e of n)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,n){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),s=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),s.set(n,!0)}addLineFlowCode(e,t=null){return""===e||(null!==t&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new fE,n=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=n,t}flowShaderNode(e){const t=e.layout,n={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(const e of t.inputs)n[e.name]=new kM(e.type,e.name);e.layout=null;const i=e.call(n),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowStagesNode(e,t=null){const n=this.flow,i=this.vars,r=this.cache,s=this.buildStage,a=this.stack,o={code:""};this.flow=o,this.vars={},this.cache=new mw,this.stack=GM();for(const n of ef)this.setBuildStage(n),o.result=e.build(this,t);return o.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=i,this.cache=r,this.stack=a,this.setBuildStage(s),o}getFunctionOperator(){return null}flowChildNode(e,t=null){const n=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=n,i}flowNodeFromShaderStage(e,t,n=null,i=null){const r=this.shaderStage;this.setShaderStage(e);const s=this.flowChildNode(t,n);return null!==i&&(s.code+=`${this.tab+i} = ${s.result};\n`),this.flowCode[e]=this.flowCode[e]+s.code,this.setShaderStage(r),s}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t,n=null){return`${null!==n?this.generateArrayDeclaration(e,n):this.getType(e)} ${t}`}getVars(e){let t="";const n=this.vars[e];if(void 0!==n)for(const e of n)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("Abstract function.")}getCodes(e){const t=this.codes[e];let n="";if(void 0!==t)for(const e of t)n+=e.code+"\n";return n}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){console.warn("Abstract function.")}build(){const{object:e,material:t,renderer:n}=this;if(null!==t){let e=n.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new _b),e.build(this)}else this.addFlow("compute",e);for(const e of ef){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of tf){this.setShaderStage(t);const n=this.flowNodes[t];for(const t of n)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new ww(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new Aw(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new Rw(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new Cw(e);if("color"===t)return new Nw(e);if("mat2"===t)return new Pw(e);if("mat3"===t)return new Dw(e);if("mat4"===t)return new Uw(e);throw new Error(`Uniform "${t}" not declared.`)}format(e,t,n){if((t=this.getVectorType(t))===(n=this.getVectorType(n))||null===n||this.isReference(n))return e;const i=this.getTypeLength(t),r=this.getTypeLength(n);return 16===i&&9===r?`${this.getType(n)}(${e}[0].xyz, ${e}[1].xyz, ${e}[2].xyz)`:9===i&&4===r?`${this.getType(n)}(${e}[0].xy, ${e}[1].xy)`:i>4||r>4||0===r?e:i===r?`${this.getType(n)}( ${e} )`:i>r?this.format(`${e}.${"xyz".slice(0,r)}`,this.getTypeFromLength(r,this.getComponentType(t)),n):4===r&&i>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${s} - Node System\n`}createNodeMaterial(e="NodeMaterial"){throw new Error(`THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${e}() instead.`)}}class Bw{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let n=e.get(t);return void 0===n&&(n={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(),n=e.updateReference(this);if(t===$p){const{frameMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(n)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(n,this.frameId)}else if(t===Yp){const{renderMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(n)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(n,this.renderId)}else t===Kp&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),n=e.updateReference(this);if(t===$p){const{frameMap:t}=this._getMaps(this.updateAfterMap,n);t.get(n)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(n,this.frameId)}else if(t===Yp){const{renderMap:t}=this._getMaps(this.updateAfterMap,n);t.get(n)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(n,this.renderId)}else t===Kp&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),n=e.updateReference(this);if(t===$p){const{frameMap:t}=this._getMaps(this.updateMap,n);t.get(n)!==this.frameId&&!1!==e.update(this)&&t.set(n,this.frameId)}else if(t===Yp){const{renderMap:t}=this._getMaps(this.updateMap,n);t.get(n)!==this.renderId&&!1!==e.update(this)&&t.set(n,this.renderId)}else t===Kp&&e.update(this)}update(){this.frameId++,void 0===this.lastTime&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class kw{constructor(e,t,n=null,i="",r=!1){this.type=e,this.name=t,this.count=n,this.qualifier=i,this.isConst=r}}kw.isNodeFunctionInput=!0;class zw extends ew{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:EE(this.light),lightColor:e}}}const Gw=new kn,Vw=new kn;let Hw=null;class jw extends ew{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Cm(new un).setGroup(wm),this.halfWidth=Cm(new un).setGroup(wm),this.updateType=Yp}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;Vw.identity(),Gw.copy(t.matrixWorld),Gw.premultiply(n),Vw.extractRotation(Gw),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(Vw),this.halfHeight.value.applyMatrix4(Vw)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=bv(Hw.LTC_FLOAT_1),n=bv(Hw.LTC_FLOAT_2)):(t=bv(Hw.LTC_HALF_1),n=bv(Hw.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:ME(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){Hw=e}}class Ww extends ew{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Cm(0).setGroup(wm),this.penumbraCosNode=Cm(0).setGroup(wm),this.cutoffDistanceNode=Cm(0).setGroup(wm),this.decayExponentNode=Cm(0).setGroup(wm)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e){const{coneCosNode:t,penumbraCosNode:n}=this;return N_(t,n,e)}setupDirect(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:i,light:r}=this,s=this.getLightVector(e),a=s.normalize(),o=a.dot(EE(r)),l=this.getSpotAttenuation(o),u=s.length(),c=tw({lightDistance:u,cutoffDistance:n,decayExponent:i});let h=t.mul(l).mul(c);if(r.map){const t=function(e,t=Wv){const n=SE(e).mul(t);return n.xyz.div(n.w)}(r,e.context.positionWorld),n=bv(r.map,t.xy).onRenderUpdate((()=>r.map));h=t.mul(2).sub(1).abs().lessThan(1).all().select(h.mul(n),h)}return{lightColor:h,lightDirection:a}}}class Xw extends Ww{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e){const t=this.light.iesMap;let n=null;if(t&&!0===t.isTexture){const i=e.acos().mul(1/Math.PI);n=bv(t,am(i,0),0).r}else n=super.getSpotAttenuation(e);return n}}class qw extends ew{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class $w extends ew{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=TE(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Cm(new Pi).setGroup(wm)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:n,lightDirectionNode:i}=this,r=ey.dot(i).mul(.5).add(.5),s=A_(n,t,r);e.context.irradiance.addAssign(s)}}class Yw extends ew{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new un);this.lightProbe=Av(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=iw(ty,this.lightProbe);e.context.irradiance.addAssign(t)}}class Kw{parseFunction(){console.warn("Abstract function.")}}class Zw{constructor(e,t,n="",i=""){this.type=e,this.inputs=t,this.name=n,this.precision=i}getCode(){console.warn("Abstract function.")}}Zw.isNodeFunction=!0;const Qw=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,Jw=/[a-z_0-9]+/gi,eA="#pragma main";class tA extends Zw{constructor(e){const{type:t,inputs:n,name:i,precision:r,inputsCode:s,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(eA),n=-1!==t?e.slice(t+12):e,i=n.match(Qw);if(null!==i&&5===i.length){const r=i[4],s=[];let a=null;for(;null!==(a=Jw.exec(r));)s.push(a);const o=[];let l=0;for(;l0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==n||i){const r=this.getCacheNode("background",n,(()=>{if(!0===n.isCubeTexture||n.mapping===j||n.mapping===W||n.mapping===X){if(e.backgroundBlurriness>0||n.mapping===X)return AT(n);{let e;return e=!0===n.isCubeTexture?_y(n):bv(n),Pb(e)}}if(!0===n.isTexture)return bv(n,Yx.flipY()).setUpdateMatrix(!0);!0!==n.isColor&&console.error("WebGPUNodes: Unsupported background configuration.",n)}),i);t.backgroundNode=r,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,i=!1){const r=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let s=r.get(t);return(void 0===s||i)&&(s=n(),r.set(t,s)),s}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){const e=this.getCacheNode("fog",n,(()=>{if(n.isFogExp2){const e=xy("color","color",n).setGroup(wm),t=xy("density","float",n).setGroup(wm);return vE(e,_E(t))}if(n.isFog){const e=xy("color","color",n).setGroup(wm),t=xy("near","float",n).setGroup(wm),i=xy("far","float",n).setGroup(wm);return vE(e,gE(t,i))}console.error("THREE.Renderer: Unsupported fog configuration.",n)}));t.fogNode=e,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),n=e.environment;if(n){if(t.environment!==n){const e=this.getCacheNode("environment",n,(()=>!0===n.isCubeTexture?_y(n):!0===n.isTexture?bv(n):void console.error("Nodes: Unsupported environment configuration.",n)));t.environmentNode=e,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,i=null,r=null){const s=this.nodeFrame;return s.renderer=e,s.scene=t,s.object=n,s.camera=i,s.material=r,s}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace}hasOutputChange(e){return iA.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,n=this.getOutputCacheKey(),i=bv(e,Yx).renderOutput(t.toneMapping,t.currentColorSpace);return iA.set(e,n),i}updateBefore(e){const t=e.getNodeBuilderState();for(const n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){const t=e.getNodeBuilderState();for(const n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateForCompute(e){const t=this.getNodeFrame(),n=this.getForCompute(e);for(const e of n.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const e of n.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new Bw,this.nodeBuilderCache=new Map,this.cacheLib={}}}const oA=new Hr;class lA{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Ot,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,n){const i=e.length;for(let r=0;r0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},r=new XRWebGLLayer(e,i,n);this._glBaseLayer=r,e.updateRenderState({baseLayer:r}),t.setPixelRatio(1),t.setSize(r.framebufferWidth,r.framebufferHeight,!1),this._xrRenderTarget=new gA(r.framebufferWidth,r.framebufferHeight,{format:ge,type:ne,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===r.ignoreDepthValues,resolveStencilBuffer:!1===r.ignoreDepthValues})}this.setFoveation(this.getFoveation()),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const n=e.near,i=e.far,r=this._cameraXR,s=this._cameraL,a=this._cameraR;r.near=a.near=s.near=n,r.far=a.far=s.far=i,this._currentDepthNear===r.near&&this._currentDepthFar===r.far||(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),s.layers.mask=2|e.layers.mask,a.layers.mask=4|e.layers.mask,r.layers.mask=s.layers.mask|a.layers.mask;const o=e.parent,l=r.cameras;xA(r,o);for(let e=0;e=0&&(n[s]=null,t[s].disconnect(r))}for(let i=0;i=n.length){n.push(r),s=e;break}if(null===n[e]){n[e]=r,s=e;break}}if(-1===s)break}const a=t[s];a&&a.connect(r)}}function MA(e,t){if(void 0===t)return;const n=this._cameraXR,i=this._renderer,r=i.backend,s=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.views;null!==this._glBaseLayer&&r.setXRTarget(s.framebuffer);let t=!1;e.length!==n.cameras.length&&(n.cameras.length=0,t=!0);for(let i=0;i{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(e,t,this._renderTarget),s=e.overrideMaterial||n.material,a=this._objects.get(n,s,e,t,i.lightsNode,r,r.clippingContext),{fragmentShader:o,vertexShader:l}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:l}}}}async init(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");return null!==this._initPromise||(this._initPromise=new Promise((async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=n=this._getFallback(e),await n.init(this)}catch(e){return void t(e)}}this._nodes=new aA(this,n),this._animation=new JT(this._nodes,this.info),this._attributes=new hM(n),this._background=new sw(this,this._nodes),this._geometries=new fM(this._attributes,this.info),this._textures=new FM(this,n,this.info),this._pipelines=new bM(n,this._nodes),this._bindings=new SM(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new rM(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new RM(this.lighting),this._bundles=new hA,this._renderContexts=new IM,this._animation.start(),this._initialized=!0,e(this)}))),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,s=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._compilationPromises,l=!0===e.isScene?e:EA;null===n&&(n=e);const u=this._renderTarget,c=this._renderContexts.get(n,t,u),h=this._activeMipmapLevel,d=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,i.renderId++,i.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new lA),c.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,u);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,c.clippingContext),n!==e&&n.traverseVisible((function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)})),p.finish(),null!==u){this._textures.updateRenderTarget(u,h);const e=this._textures.get(u);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;this._background.update(l,p,c);const f=p.opaque,m=p.transparent,g=p.transparentDoublePass,_=p.lightsNode;!0===this.opaque&&f.length>0&&this._renderObjects(f,t,l,_),!0===this.transparent&&m.length>0&&this._renderTransparents(m,g,t,l,_),i.renderId=r,this._currentRenderContext=s,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){!1===this._initialized&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,n){const{bundleGroup:i,camera:r,renderList:s}=e,a=this._currentRenderContext,o=this._bundles.get(i,r),l=this.backend.get(o);void 0===l.renderContexts&&(l.renderContexts=new Set);const u=i.version!==l.version,c=!1===l.renderContexts.has(a)||u;if(l.renderContexts.add(a),c){this.backend.beginBundle(a),(void 0===l.renderObjects||u)&&(l.renderObjects=[]),this._currentRenderBundle=o;const e=s.opaque;!0===this.opaque&&e.length>0&&this._renderObjects(e,r,t,n),this._currentRenderBundle=null,this.backend.finishBundle(a,o),l.version=i.version}else{const{renderObjects:e}=l;for(let t=0,n=e.length;t>=h,p.viewportValue.height>>=h,p.viewportValue.minDepth=y,p.viewportValue.maxDepth=x,p.viewport=!1===p.viewportValue.equals(AA),p.scissorValue.copy(_).multiplyScalar(v).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(AA),p.scissorValue.width>>=h,p.scissorValue.height>>=h,p.clippingContext||(p.clippingContext=new lA),p.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d),CA.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),RA.setFromProjectionMatrix(CA,f);const b=this._renderLists.get(e,t);if(b.begin(),this._projectObject(e,t,0,b,p.clippingContext),b.finish(),!0===this.sortObjects&&b.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,h);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=h,p.height>>=h,p.activeCubeFace=c,p.activeMipmapLevel=h,p.occlusionQueryCount=b.occlusionQueryCount,this._background.update(l,b,p),this.backend.beginRender(p);const{bundles:S,lightsNode:T,transparentDoublePass:M,transparent:E,opaque:w}=b;return S.length>0&&this._renderBundles(S,l,T),!0===this.opaque&&w.length>0&&this._renderObjects(w,t,l,T),!0===this.transparent&&E.length>0&&this._renderTransparents(E,M,t,l,T),this.backend.finishRender(p),r.renderId=s,this._currentRenderContext=a,this._currentRenderObjectFunction=o,null!==i&&(this.setRenderTarget(u,c,h),this._renderOutput(d)),l.onAfterRender(this,e,t,d),p}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const n=this.autoClear,i=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=n,this.xr.enabled=i}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,n){this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setSize(e,t,n=!0){this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===n&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize()}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,n,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,n,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,i,r=0,s=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,i),a.minDepth=r,a.maxDepth=s}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(!1===this._initialized)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,n);const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i){this._textures.updateRenderTarget(i);const e=this._textures.get(i);r=this._renderContexts.getForClear(i),r.textures=e.textures,r.depthTexture=e.depthTexture,r.width=e.width,r.height=e.height,r.renderTarget=i,r.depth=i.depthBuffer,r.stencil=i.stencilBuffer,r.clearColorValue=this.backend.getClearColor()}this.backend.clear(e,t,n,r),null!==i&&null===this._renderTarget&&this._renderOutput(i)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){!1===this._initialized&&await this.init(),this.clear(e,t,n)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:at}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach((e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,n=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const i=this.backend,r=this._pipelines,s=this._bindings,a=this._nodes,o=Array.isArray(e)?e:[e];if(void 0===o[0]||!0!==o[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const t of o){if(!1===r.has(t)){const e=()=>{t.removeEventListener("dispose",e),r.delete(t),s.delete(t),a.delete(t)};t.addEventListener("dispose",e);const n=t.onInitFunction;null!==n&&n.call(t,{renderer:this})}a.updateForCompute(t),s.updateForCompute(t);const n=s.getForCompute(t),o=r.getForCompute(t,n);i.compute(e,t,n,o)}i.finishCompute(e),t.renderId=n}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return!1===this._initialized?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){!1===this._initialized&&await this.init(),this._textures.updateTexture(e)}initTexture(e){!1===this._initialized&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=NA.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");t=NA.copy(t).floor()}else t=NA.set(0,0,e.image.width,e.image.height);let n,i=this._currentRenderContext;null!==i?n=i.renderTarget:(n=this._renderTarget||this._getFrameBufferTarget(),null!==n&&(this._textures.updateRenderTarget(n),i=this._textures.get(n))),this._textures.updateTexture(e,{renderTarget:n}),this.backend.copyFramebufferToTexture(e,i,t)}copyTextureToTexture(e,t,n=null,i=null,r=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,i,r)}async readRenderTargetPixelsAsync(e,t,n,i,r,s=0,a=0){return this.backend.copyTextureToBuffer(e.textures[s],t,n,i,r,a)}_projectObject(e,t,n,i,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(r=r.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){if(!e.frustumCulled||RA.intersectsSprite(e)){!0===this.sortObjects&&NA.setFromMatrixPosition(e.matrixWorld).applyMatrix4(CA);const{geometry:t,material:s}=e;s.visible&&i.push(e,t,s,n,NA.z,null,r)}}else if(e.isLineLoop)console.error("THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||RA.intersectsObject(e))){const{geometry:t,material:s}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),NA.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(CA)),Array.isArray(s)){const a=t.groups;for(let o=0,l=a.length;o0){for(const{material:e}of t)e.side=1;this._renderObjects(t,n,i,r,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,n,i,r);for(const{material:e}of t)e.side=2}else this._renderObjects(e,n,i,r)}_renderObjects(e,t,n,i,r=null){for(let s=0,a=e.length;s0,e.isShadowPassMaterial&&(e.side=null===r.shadowSide?r.side:r.shadowSide,r.depthNode&&r.depthNode.isNode&&(h=e.depthNode,e.depthNode=r.depthNode),r.castShadowNode&&r.castShadowNode.isNode&&(c=e.colorNode,e.colorNode=r.castShadowNode)),r=e}!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,this._handleObjectFunction(e,r,t,n,a,s,o,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,n,a,s,o,l),r.side=2):this._handleObjectFunction(e,r,t,n,a,s,o,l),void 0!==u&&(t.overrideMaterial.positionNode=u),void 0!==h&&(t.overrideMaterial.depthNode=h),void 0!==c&&(t.overrideMaterial.colorNode=c),e.onAfterRender(this,t,n,i,r,s)}_renderObjectDirect(e,t,n,i,r,s,a,o){const l=this._objects.get(e,t,n,i,r,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s;const u=this._nodes.needsRefresh(l);if(u&&(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)),this._pipelines.updateForRender(l),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(l,this.info),u&&this._nodes.updateAfter(l)}_createObjectPipeline(e,t,n,i,r,s,a,o){const l=this._objects.get(e,t,n,i,r,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s,this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l),this._pipelines.getForRender(l,this._compilationPromises),this._nodes.updateAfter(l)}get compile(){return this.compileAsync}}class DA{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class UA extends DA{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(cM-e%cM)%cM;var e}get buffer(){return this._buffer}update(){return!0}}class LA extends UA{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let IA=0;class OA extends LA{constructor(e,t){super("UniformBuffer_"+IA++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class FA extends LA{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){let e=0;for(let t=0,n=this.uniforms.length;t0?i:"";t=`${e.name} {\n\t${n} ${r.name}[${s}];\n};\n`}else{t=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,s=!0}const a=r.node.precision;if(null!==a&&(t=XA[a]+" "+t),s){t="\t"+t;const e=r.groupNode.name;(i[e]||(i[e]=[])).push(t)}else t="uniform "+t,n.push(t)}let r="";for(const t in i){const n=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,n.join("\n"))+"\n"}return r+=n.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==ae){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const i=n.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let n=0;for(const i of e)t+=`layout( location = ${n++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[];for(const n of e.members)t.push(`\t${n.type} ${n.name};`);return t.join("\n")}getStructs(e){const t=[],n=this.structs[e],i=[];for(const e of n)if(e.output)for(const t of e.members)i.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let n="struct "+e.name+" {\n";n+=this.getStructMembers(e),n+="\n};\n",t.push(n)}return 0===i.length&&i.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+i.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const n=this.varyings;if("vertex"===e||"compute"===e)for(const i of n){"compute"===e&&(i.needsInterpolation=!0);const n=this.getType(i.type);if(i.needsInterpolation){t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""} out ${n} ${i.name};\n`}else t+=`${n} ${i.name};\n`}else if("fragment"===e)for(const e of n)if(e.needsInterpolation){const n=this.getType(e.type);t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}in ${n} ${e.name};\n`}for(const n of this.builtins[e])t+=`${n};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce(((e,t)=>e*t),1)}u`}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){const i=this.extensions[n]||(this.extensions[n]=new Map);!1===i.has(e)&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if("vertex"===e){const t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const n=this.extensions[e];if(void 0!==n)for(const{name:e,behavior:i}of n.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=qA[e];if(void 0===t){let n;switch(t=!1,e){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance"}if(void 0!==n){const e=this.renderer.backend.extensions;e.has(n)&&(e.get(n),t=!0)}qA[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let n=0;n0&&(n+="\n"),n+=`\t// flow -> ${s}\n\t`),n+=`${i.code}\n\t`,e===r&&"compute"!==t&&(n+="// result\n\t","vertex"===t?(n+="gl_Position = ",n+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${i.result};`)))}const s=e[t];s.extensions=this.getExtensions(t),s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.vars=this.getVars(t),s.structs=this.getStructs(t),s.codes=this.getCodes(t),s.transforms=this.getTransforms(t),s.flow=n}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);let a=s.uniformGPU;if(void 0===a){const i=e.groupNode,o=i.name,l=this.getBindGroupArray(o,n);if("texture"===t)a=new VA(r.name,r.node,i),l.push(a);else if("cubeTexture"===t)a=new HA(r.name,r.node,i),l.push(a);else if("texture3D"===t)a=new jA(r.name,r.node,i),l.push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,r.name=`buffer${e.id}`;const t=new OA(e,i);t.name=e.name,l.push(t),a=t}else{const e=this.uniformGroups[n]||(this.uniformGroups[n]={});let s=e[o];void 0===s&&(s=new kA(n+"_"+o,i),e[o]=s,l.push(s)),a=this.getNodeUniform(r,t),s.addUniform(a)}s.uniformGPU=a}return r}}let KA=null,ZA=null;class QA{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute:null}}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void Vt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return void Vt(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);const n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return KA=KA||new It,this.renderer.getDrawingBufferSize(KA)}setScissorTest(){}getClearColor(){const e=this.renderer;return ZA=ZA||new BM,e.getClearColor(ZA),ZA.getRGB(ZA),ZA}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:zt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${s} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let JA,eR,tR=0;class nR{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class iR{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:i}=n,r=e.array,s=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=n.get(a);let l,u=o.bufferGPU;if(void 0===u&&(u=this._createBuffer(i,t,r,s),o.bufferGPU=u,o.bufferType=t,o.version=a.version),r instanceof Float32Array)l=i.FLOAT;else if(r instanceof Uint16Array)l=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)l=i.SHORT;else if(r instanceof Uint32Array)l=i.UNSIGNED_INT;else if(r instanceof Int32Array)l=i.INT;else if(r instanceof Int8Array)l=i.BYTE;else if(r instanceof Uint8Array)l=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);l=i.UNSIGNED_BYTE}let c={bufferGPU:u,bufferType:t,type:l,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===i.INT||l===i.UNSIGNED_INT||e.gpuType===ae,id:tR++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,s);c=new nR(c,e)}n.set(e,c)}updateAttribute(e){const t=this.backend,{gl:n}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,s=t.get(r),a=s.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,s.bufferGPU),0===o.length)n.bufferSubData(a,0,i);else{for(let e=0,t=o.length;e1?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),n>0&&this.currentClippingPlanes!==n){const e=12288;for(let t=0;t<8;t++)t{!function r(){const s=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(s===e.WAIT_FAILED)return e.deleteSync(t),void i();s!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),n()):requestAnimationFrame(r)}()}))}}let aR,oR,lR,uR=!1;class cR{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===uR&&(this._init(),uR=!0)}_init(){const e=this.gl;aR={[q]:e.REPEAT,[$]:e.CLAMP_TO_EDGE,[Y]:e.MIRRORED_REPEAT},oR={[K]:e.NEAREST,[Z]:e.NEAREST_MIPMAP_NEAREST,[Q]:e.NEAREST_MIPMAP_LINEAR,[J]:e.LINEAR,[ee]:e.LINEAR_MIPMAP_NEAREST,[te]:e.LINEAR_MIPMAP_LINEAR},lR={[ct]:e.NEVER,[_t]:e.ALWAYS,[ht]:e.LESS,[pt]:e.LEQUAL,[dt]:e.EQUAL,[gt]:e.GEQUAL,[ft]:e.GREATER,[mt]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let n;return n=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,n}getInternalFormat(e,t,n,i,r=!1){const{gl:s,extensions:a}=this;if(null!==e){if(void 0!==s[e])return s[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;return t===s.RED&&(n===s.FLOAT&&(o=s.R32F),n===s.HALF_FLOAT&&(o=s.R16F),n===s.UNSIGNED_BYTE&&(o=s.R8),n===s.UNSIGNED_SHORT&&(o=s.R16),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RED_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.R8UI),n===s.UNSIGNED_SHORT&&(o=s.R16UI),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RG&&(n===s.FLOAT&&(o=s.RG32F),n===s.HALF_FLOAT&&(o=s.RG16F),n===s.UNSIGNED_BYTE&&(o=s.RG8),n===s.UNSIGNED_SHORT&&(o=s.RG16),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RG_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RG8UI),n===s.UNSIGNED_SHORT&&(o=s.RG16UI),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RGB&&(n===s.FLOAT&&(o=s.RGB32F),n===s.HALF_FLOAT&&(o=s.RGB16F),n===s.UNSIGNED_BYTE&&(o=s.RGB8),n===s.UNSIGNED_SHORT&&(o=s.RGB16),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I),n===s.UNSIGNED_BYTE&&(o=i===st&&!1===r?s.SRGB8:s.RGB8),n===s.UNSIGNED_SHORT_5_6_5&&(o=s.RGB565),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGB4),n===s.UNSIGNED_INT_5_9_9_9_REV&&(o=s.RGB9_E5)),t===s.RGB_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGB8UI),n===s.UNSIGNED_SHORT&&(o=s.RGB16UI),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I)),t===s.RGBA&&(n===s.FLOAT&&(o=s.RGBA32F),n===s.HALF_FLOAT&&(o=s.RGBA16F),n===s.UNSIGNED_BYTE&&(o=s.RGBA8),n===s.UNSIGNED_SHORT&&(o=s.RGBA16),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I),n===s.UNSIGNED_BYTE&&(o=i===st&&!1===r?s.SRGB8_ALPHA8:s.RGBA8),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGBA4),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1)),t===s.RGBA_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGBA8UI),n===s.UNSIGNED_SHORT&&(o=s.RGBA16UI),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I)),t===s.DEPTH_COMPONENT&&(n===s.UNSIGNED_SHORT&&(o=s.DEPTH_COMPONENT16),n===s.UNSIGNED_INT&&(o=s.DEPTH_COMPONENT24),n===s.FLOAT&&(o=s.DEPTH_COMPONENT32F)),t===s.DEPTH_STENCIL&&n===s.UNSIGNED_INT_24_8&&(o=s.DEPTH24_STENCIL8),o!==s.R16F&&o!==s.R32F&&o!==s.RG16F&&o!==s.RG32F&&o!==s.RGBA16F&&o!==s.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:n,extensions:i,backend:r}=this;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,n.NONE),n.texParameteri(e,n.TEXTURE_WRAP_S,aR[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,aR[t.wrapT]),e!==n.TEXTURE_3D&&e!==n.TEXTURE_2D_ARRAY||n.texParameteri(e,n.TEXTURE_WRAP_R,aR[t.wrapR]),n.texParameteri(e,n.TEXTURE_MAG_FILTER,oR[t.magFilter]);const s=void 0!==t.mipmaps&&t.mipmaps.length>0,a=t.minFilter===J&&s?te:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,oR[a]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,lR[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===K)return;if(t.minFilter!==Q&&t.minFilter!==te)return;if(t.type===le&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const s=i.get("EXT_texture_filter_anisotropic");n.texParameterf(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:i}=this,r=this.getGLTextureType(e);let s=i[r];void 0===s&&(s=t.createTexture(),n.state.bindTexture(r,s),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=s),n.set(e,{textureGPU:s,glTextureType:r,isDefault:!0})}createTexture(e,t){const{gl:n,backend:i}=this,{levels:r,width:s,height:a,depth:o}=t,l=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),c=this.getInternalFormat(e.internalFormat,l,u,e.colorSpace,e.isVideoTexture),h=n.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,h),this.setTextureParameters(d,e),e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,r,c,s,a,o):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,r,c,s,a,o):e.isVideoTexture||n.texStorage2D(d,r,c,s,a),i.set(e,{textureGPU:h,glTextureType:d,glFormat:l,glType:u,glInternalFormat:c})}copyBufferToTexture(e,t){const{gl:n,backend:i}=this,{textureGPU:r,glTextureType:s,glFormat:a,glType:o}=i.get(t),{width:l,height:u}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(s,r),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(s,0,0,0,l,u,a,o,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:i,height:r}=t,{textureGPU:s,glTextureType:a,glFormat:o,glType:l,glInternalFormat:u}=this.backend.get(e);if(e.isRenderTargetTexture||void 0===s)return;const c=e=>e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||e instanceof OffscreenCanvas?e:e.data;if(this.backend.state.bindTexture(a,s),this.setTextureParameters(a,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t0,h=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(c){const n=0!==a||0!==o;let c,d;if(!0===e.isDepthTexture?(c=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(c|=i.STENCIL_BUFFER_BIT)):(c=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),n){const e=this.backend.get(t.renderTarget),n=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,n),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=h-o-u;i.blitFramebuffer(a,p,a+l,p+u,a,p,a+l,p+u,c,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,n),r.bindTexture(i.TEXTURE_2D,s),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,p,l,u),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,s,0),i.blitFramebuffer(0,0,l,u,0,0,l,u,c,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,s),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,h-u-o,l,u),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,i=!1){const{gl:r}=this,s=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:l,width:u,height:c}=s;if(r.bindRenderbuffer(r.RENDERBUFFER,e),o&&!l){let t=r.DEPTH_COMPONENT24;if(!0===i){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,s.samples,t,u,c)}else n>0?(a&&a.isDepthTexture&&a.type===r.FLOAT&&(t=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,n,t,u,c)):r.renderbufferStorage(r.RENDERBUFFER,t,u,c);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else o&&l&&(n>0?r.renderbufferStorageMultisample(r.RENDERBUFFER,n,r.DEPTH24_STENCIL8,u,c):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,u,c),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,e))}async copyTextureToBuffer(e,t,n,i,r,s){const{backend:a,gl:o}=this,{textureGPU:l,glFormat:u,glType:c}=this.backend.get(e),h=o.createFramebuffer();o.bindFramebuffer(o.READ_FRAMEBUFFER,h);const d=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+s:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,d,l,0);const p=this._getTypedArrayType(c),f=i*r*this._getBytesPerTexel(c,u),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,f,o.STREAM_READ),o.readPixels(t,n,i,r,u,c,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const g=new p(f/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,g),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteFramebuffer(h),g}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:n}=this;let i=0;return e===n.UNSIGNED_BYTE&&(i=1),e!==n.UNSIGNED_SHORT_4_4_4_4&&e!==n.UNSIGNED_SHORT_5_5_5_1&&e!==n.UNSIGNED_SHORT_5_6_5&&e!==n.UNSIGNED_SHORT&&e!==n.HALF_FLOAT||(i=2),e!==n.UNSIGNED_INT&&e!==n.FLOAT||(i=4),t===n.RGBA?4*i:t===n.RGB?3*i:t===n.ALPHA?i:void 0}}class hR{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return void 0===t&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class dR{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const pR={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query"};class fR{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:n,mode:i,object:r,type:s,info:a,index:o}=this;0!==o?n.drawElements(i,t,s,e):n.drawArrays(i,e,t),a.update(r,t,1)}renderInstances(e,t,n){const{gl:i,mode:r,type:s,index:a,object:o,info:l}=this;0!==n&&(0!==a?i.drawElementsInstanced(r,t,s,e,n):i.drawArraysInstanced(r,e,t,n),l.update(o,t,n))}renderMultiDraw(e,t,n){const{extensions:i,mode:r,object:s,info:a}=this;if(0===n)return;const o=i.get("WEBGL_multi_draw");if(null===o)for(let i=0;ithis.maxQueries)return Vt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null==t)return;if(null!==this.activeQuery)return;const n=this.queries[t];if(n)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){console.error("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){console.error("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=[];for(const[t,n]of this.queryStates)if("ended"===n){const n=this.queries[t];e.push(this.resolveQuery(n))}if(0===e.length)return this.lastValue;const t=(await Promise.all(e)).reduce(((e,t)=>e+t),0);return this.lastValue=t,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,t}catch(e){return console.error("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise((t=>{if(this.isDisposed)return void t(this.lastValue);let n,i=!1;const r=e=>{i||(i=!0,n&&(clearTimeout(n),n=null),t(e))},s=()=>{if(this.isDisposed)r(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void r(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(n=setTimeout(s,1));const i=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(i)/1e6)}catch(e){console.error("Error checking query:",e),t(this.lastValue)}};s()}))}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class _R extends QA{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this.trackTimestamp=!0===e.trackTimestamp,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,n={antialias:e.samples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=void 0!==t.context?t.context:e.domElement.getContext("webgl2",n);function r(t){t.preventDefault();const n={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(n)}this._onContextLost=r,e.domElement.addEventListener("webglcontextlost",r,!1),this.gl=i,this.extensions=new hR(this),this.capabilities=new dR(this),this.attributeUtils=new iR(this),this.textureUtils=new cR(this),this.bufferRenderer=new fR(this),this.state=new rR(this),this.utils=new sR(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return bt}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),null!==n){const t=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:t}),e.autoAllocateDepthBuffer=!1,!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided")}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new gR(this.gl,t,2048));const n=this.timestampQueryPool[t];null!==n.allocateQueriesForContext(e)&&n.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t,gl:n}=this,i=this.get(e);if(e.viewport?this.updateViewport(e):t.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),e.scissor){const{x:n,y:i,width:r,height:s}=e.scissorValue;t.scissor(n,e.height-s-i,r,s)}this.initTimestampQuery(e),i.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const r=e.occlusionQueryCount;r>0&&(i.currentOcclusionQueries=i.occlusionQueries,i.currentOcclusionQueryObjects=i.occlusionQueryObjects,i.lastOcclusionObject=null,i.occlusionQueries=new Array(r),i.occlusionQueryObjects=new Array(r),i.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:n}=this,i=this.get(e),r=i.previousContext;n.resetVertexState();const s=e.occlusionQueryCount;s>0&&(s>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(null!==a)for(let e=0;e0&&!1===this._useMultisampledRTT(e.renderTarget)){const r=i.framebuffers[e.getCacheKey()],s=t.COLOR_BUFFER_BIT,a=i.msaaFrameBuffer,o=e.textures;n.bindFramebuffer(t.READ_FRAMEBUFFER,a),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,r);for(let n=0;n{let a=0;for(let t=0;t{t.isBatchedMesh?null!==t._multiDrawInstances?(Vt("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),_.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?_.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):Vt("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):y>1?_.renderInstances(x,v,y):_.render(x,v)};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const n=this.get(e.camera),i=e.camera.cameras,r=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===n.indexesGPU||n.indexesGPU.length!==i.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let n=0,r=i.length;n{const r=this.parallel,s=()=>{n.getProgramParameter(a,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(s)};s()}));t.push(r)}else this._completeCompile(e,i)}_handleSource(e,t){const n=e.split("\n"),i=[],r=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let e=r;e":" "} ${r}: ${n[e]}`)}return i.join("\n")}_getShaderErrors(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=e.getShaderInfoLog(t).trim();if(i&&""===r)return"";const s=/ERROR: 0:(\d+)/.exec(r);if(s){const i=parseInt(s[1]);return n.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=i.getProgramInfoLog(e).trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,n,t);else{const s=this._getShaderErrors(i,n,"vertex"),a=this._getShaderErrors(i,t,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+s+"\n"+a)}else""!==r&&console.warn("THREE.WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:n,gl:i}=this,r=this.get(t),{programGPU:s,fragmentShader:a,vertexShader:o}=r;!1===i.getProgramParameter(s,i.LINK_STATUS)&&this._logProgramError(s,a,o),n.useProgram(s);const l=e.getBindings();this._setupBindings(l,s),this.set(t,{programGPU:s})}createComputePipeline(e,t){const{state:n,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:s}=e,a=i.createProgram(),o=this.get(r).shaderGPU,l=this.get(s).shaderGPU,u=s.transforms,c=[],h=[];for(let e=0;epR[t]===e)),n=this.extensions;for(let e=0;e0&&!1===_){if(void 0===f){const i=[];f=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,f);const r=[],u=e.textures;for(let n=0;n0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e.autoAllocateDepthBuffer}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const vR="point-list",yR="line-list",xR="line-strip",bR="triangle-list",SR="triangle-strip",TR="never",MR="less",ER="equal",wR="less-equal",AR="greater",RR="not-equal",CR="greater-equal",NR="always",PR="store",DR="load",UR="clear",LR="ccw",IR="none",OR="front",FR="back",BR="uint16",kR="uint32",zR={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},GR="clamp-to-edge",VR="repeat",HR="mirror-repeat",jR="linear",WR="nearest",XR="zero",qR="one",$R="src",YR="one-minus-src",KR="src-alpha",ZR="one-minus-src-alpha",QR="dst",JR="one-minus-dst",eC="dst-alpha",tC="one-minus-dst-alpha",nC="src-alpha-saturated",iC="constant",rC="one-minus-constant",sC="add",aC="subtract",oC="reverse-subtract",lC="min",uC="max",cC=0,hC=15,dC="keep",pC="zero",fC="replace",mC="invert",gC="increment-clamp",_C="decrement-clamp",vC="increment-wrap",yC="decrement-wrap",xC="storage",bC="read-only-storage",SC="write-only",TC="read-only",MC="read-write",EC="float",wC="unfilterable-float",AC="depth",RC="sint",CC="uint",NC="2d",PC="3d",DC="2d",UC="2d-array",LC="cube",IC="3d",OC="all",FC="vertex",BC="instance",kC={DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups"};class zC extends DA{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class GC extends zC{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){this.texture=this.textureNode.value}}class VC extends UA{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let HC=0;class jC extends VC{constructor(e,t){super("StorageBuffer_"+HC++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Jp,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class WC extends sM{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:jR}),this.flipYSampler=e.createSampler({minFilter:WR}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4,\n\t@location( 0 ) vTex : vec2\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2, 4 >(\n\t\tvec2( -1.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 ),\n\t\tvec2( -1.0, -1.0 ),\n\t\tvec2( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2, 4 >(\n\t\tvec2( 0.0, 0.0 ),\n\t\tvec2( 1.0, 0.0 ),\n\t\tvec2( 0.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:SR,stripIndexFormat:kR},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:SR,stripIndexFormat:kR},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,n=0){const i=t.format,{width:r,height:s}=t.size,a=this.getTransferPipeline(i),o=this.getFlipYPipeline(i),l=this.device.createTexture({size:{width:r,height:s,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),u=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:DC,baseArrayLayer:n}),c=l.createView({baseMipLevel:0,mipLevelCount:1,dimension:DC,baseArrayLayer:0}),h=this.device.createCommandEncoder({}),d=(e,t,n)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),s=h.beginRenderPass({colorAttachments:[{view:n,loadOp:UR,storeOp:PR,clearValue:[0,0,0,0]}]});s.setPipeline(e),s.setBindGroup(0,r),s.draw(4,1,0,0),s.end()};d(a,u,c),d(o,c,u),this.device.queue.submit([h.finish()]),l.destroy()}generateMipmaps(e,t,n=0){const i=this.get(e);void 0===i.useCount&&(i.useCount=0,i.layers=[]);const r=i.layers[n]||this._mipmapCreateBundles(e,t,n),s=this.device.createCommandEncoder({});this._mipmapRunBundles(s,r),this.device.queue.submit([s.finish()]),0!==i.useCount&&(i.layers[n]=r),i.useCount++}_mipmapCreateBundles(e,t,n){const i=this.getTransferPipeline(t.format),r=i.getBindGroupLayout(0);let s=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:DC,baseArrayLayer:n});const a=[];for(let o=1;o1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,ZC=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,QC={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2":"vec2","vec2":"ivec2","vec2":"uvec2","vec2":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3":"vec3","vec3":"ivec3","vec3":"uvec3","vec3":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4":"vec4","vec4":"ivec4","vec4":"uvec4","vec4":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2":"mat2",mat2x2f:"mat2","mat3x3":"mat3",mat3x3f:"mat3","mat4x4":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class JC extends Zw{constructor(e){const{type:t,inputs:n,name:i,inputsCode:r,blockCode:s,outputType:a}=(e=>{const t=(e=e.trim()).match(KC);if(null!==t&&4===t.length){const n=t[2],i=[];let r=null;for(;null!==(r=ZC.exec(n));)i.push({name:r[1],type:r[2]});const s=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class eN extends Kw{parseFunction(e){return new JC(e)}}const tN="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},nN={[Zp]:"read",[Qp]:"write",[Jp]:"read_write"},iN={[q]:"repeat",[$]:"clamp",[Y]:"mirror"},rN={vertex:tN?tN.VERTEX:1,fragment:tN?tN.FRAGMENT:2,compute:tN?tN.COMPUTE:4},sN={instance:!0,swizzleAssign:!1,storageBuffer:!0},aN={"^^":"tsl_xor"},oN={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3",vec2:"vec2",ivec2:"vec2",uvec2:"vec2",bvec2:"vec2",vec3:"vec3",ivec3:"vec3",uvec3:"vec3",bvec3:"vec3",vec4:"vec4",ivec4:"vec4",uvec4:"vec4",bvec4:"vec4",mat2:"mat2x2",mat3:"mat3x3",mat4:"mat4x4"},lN={},uN={tsl_xor:new pE("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new pE("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new pE("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new pE("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new pE("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new pE("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new pE("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new pE("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new pE("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4 { return vec4( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new pE("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new pE("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new pE("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new pE("\nfn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},cN={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast"};"undefined"!=typeof navigator&&/Windows/g.test(navigator.userAgent)&&(uN.pow_float=new pE("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),uN.pow_vec2=new pE("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[uN.pow_float]),uN.pow_vec3=new pE("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[uN.pow_float]),uN.pow_vec4=new pE("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[uN.pow_float]),cN.pow_float="tsl_pow_float",cN.pow_vec2="tsl_pow_vec2",cN.pow_vec3="tsl_pow_vec3",cN.pow_vec4="tsl_pow_vec4");let hN="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(hN+="diagnostic( off, derivative_uniformity );\n");class dN extends Fw{constructor(e,t){super(e,t,new eN),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==rt}_generateTextureSample(e,t,n,i,r=this.shaderStage){return"fragment"===r?i?`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n):this.generateTextureLod(e,t,n,i,"0")}_generateVideoSample(e,t,n=this.shaderStage){if("fragment"===n)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${n} shader.`)}_generateTextureSampleLevel(e,t,n,i,r,s=this.shaderStage){return"fragment"!==s&&"compute"!==s||!1!==this.isUnfilterable(e)?this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,i):this.generateTextureLod(e,t,n,r,i):`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`}generateWrapFunction(e){const t=`tsl_coord_${iN[e.wrapS]}S_${iN[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let n=lN[t];if(void 0===n){const i=[],r=e.isData3DTexture?"vec3f":"vec2f";let s=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const a=(e,t)=>{e===q?(i.push(uN.repeatWrapping_float),s+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===$?(i.push(uN.clampWrapping_float),s+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===Y?(i.push(uN.mirrorWrapping_float),s+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(s+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),s+=",\n",a(e.wrapT,"y"),e.isData3DTexture&&(s+=",\n",a(e.wrapR,"z")),s+="\n\t);\n\n}\n",lN[t]=n=new pE(s,i)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){const i=this.getDataFromNode(e,this.shaderStage,this.globalCache);void 0===i.dimensionsSnippet&&(i.dimensionsSnippet={});let r=i.dimensionsSnippet[n];if(void 0===i.dimensionsSnippet[n]){let s,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),l=o>1;a=e.isData3DTexture?"vec3":"vec2",s=l||e.isVideoTexture||e.isStorageTexture?t:`${t}${n?`, u32( ${n} )`:""}`,r=new F_(new cv(`textureDimensions( ${s} )`,a)),i.dimensionsSnippet[n]=r,(e.isDataArrayTexture||e.isData3DTexture)&&(i.arrayLayerCount=new F_(new cv(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new F_(new cv("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,n,i="0u"){this._include("biquadraticTexture");return`tsl_biquadraticTexture( ${t}, ${this.generateWrapFunction(e)}( ${n} ), ${this.generateTextureDimension(e,t,i)}, u32( ${i} ) )`}generateTextureLod(e,t,n,i,r="0u"){const s=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,r),o=e.isData3DTexture?"vec3":"vec2",l=`${o}(${s}(${n}) * ${o}(${a}))`;return this.generateTextureLoad(e,t,l,i,r)}generateTextureLoad(e,t,n,i,r="0u"){return!0===e.isVideoTexture||!0===e.isStorageTexture?`textureLoad( ${t}, ${n} )`:i?`textureLoad( ${t}, ${n}, ${i}, u32( ${r} ) )`:`textureLoad( ${t}, ${n}, u32( ${r} ) )`}generateTextureStore(e,t,n,i){return`textureStore( ${t}, ${n}, ${i} )`}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===le||!1===this.isSampleCompare(e)&&e.minFilter===K&&e.magFilter===K||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,n,i,r=this.shaderStage){let s=null;return s=!0===e.isVideoTexture?this._generateVideoSample(t,n,r):this.isUnfilterable(e)?this.generateTextureLod(e,t,n,i,"0",r):this._generateTextureSample(e,t,n,i,r),s}generateTextureGrad(e,t,n,i,r,s=this.shaderStage){if("fragment"===s)return`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${s} shader.`)}generateTextureCompare(e,t,n,i,r,s=this.shaderStage){if("fragment"===s)return`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${s} shader.`)}generateTextureLevel(e,t,n,i,r,s=this.shaderStage){let a=null;return a=!0===e.isVideoTexture?this._generateVideoSample(t,n,s):this._generateTextureSampleLevel(e,t,n,i,r,s),a}generateTextureBias(e,t,n,i,r,s=this.shaderStage){if("fragment"===s)return`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${s} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,n=e.type;return"texture"===n||"cubeTexture"===n||"storageTexture"===n||"texture3D"===n?t:"buffer"===n||"storageBuffer"===n||"indirectStorageBuffer"===n?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=aN[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?Zp:e.access}getStorageAccess(e,t){return nN[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,i=null){const r=super.getUniformFromNode(e,t,n,i),s=this.getDataFromNode(e,n,this.globalCache);if(void 0===s.uniformGPU){let a;const o=e.groupNode,l=o.name,u=this.getBindGroupArray(l,n);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let i=null;const s=this.getNodeAccess(e,n);if("texture"===t||"storageTexture"===t?i=new VA(r.name,r.node,o,s):"cubeTexture"===t?i=new HA(r.name,r.node,o,s):"texture3D"===t&&(i=new jA(r.name,r.node,o,s)),i.store=!0===e.isStorageTextureNode,i.setVisibility(rN[n]),"fragment"!==n&&"compute"!==n||!1!==this.isUnfilterable(e.value)||!1!==i.store)u.push(i),a=[i];else{const e=new GC(`${r.name}_sampler`,r.node,o);e.setVisibility(rN[n]),u.push(e,i),a=[e,i]}}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const s=new("buffer"===t?OA:jC)(e,o);s.setVisibility(rN[n]),u.push(s),a=s,r.name=i||"NodeBuffer_"+r.id}else{const e=this.uniformGroups[n]||(this.uniformGroups[n]={});let i=e[l];void 0===i&&(i=new kA(l,o),i.setVisibility(rN[n]),e[l]=i,u.push(i)),a=this.getNodeUniform(r,t),i.addUniform(a)}s.uniformGPU=a}return r}getBuiltin(e,t,n,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:n}),t}hasBuiltin(e,t=this.shaderStage){return void 0!==this.builtins[t]&&this.builtins[t].has(e)}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${n.vars}\n${n.code}\n`;return n.result&&(r+=`\treturn ${n.result};\n`),r+="\n}\n",r}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],n=this.directives[e];if(void 0!==n)for(const e of n)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array`,"vertex")}getBuiltins(e){const t=[],n=this.builtins[e];if(void 0!==n)for(const{name:e,property:i,type:r}of n.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,n,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:n,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const s=this.getType(i);t.push(`var<${n}> ${e}: array< ${s}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3","attribute"),this.getBuiltin("local_invocation_id","localId","vec3","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const n=this.getAttributesArray();for(let e=0,i=n.length;e"),t.push(`\t${i+n.name} : ${r}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const n=this.structs[e];if(n.length>0){const e=[];for(const t of n){let n=`struct ${t.name} {\n`;n+=this.getStructMembers(t),n+="\n};",e.push(n)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,n=null){let i=`var ${t} : `;return i+=null!==n?this.generateArrayDeclaration(e,n):this.getType(e),i}getVars(e){const t=[],n=this.vars[e];if(void 0!==n)for(const e of n)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4","vertex"),"vertex"===e||"fragment"===e){const n=this.varyings,i=this.vars[e];for(let r=0;r1&&(s="_multisampled"),!0===t.isCubeTexture)i="texture_cube";else if(!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array";else if(!0===t.isDepthTexture)i=`texture_depth${s}_2d`;else if(!0===t.isVideoTexture)i="texture_external";else if(!0===t.isData3DTexture)i="texture_3d";else if(!0===r.node.isStorageTextureNode){i=`texture_storage_2d<${YC(t)}, ${this.getStorageAccess(r.node,e)}>`}else{i=`texture${s}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type||"indirectStorageBuffer"===r.type){const t=r.node,n=this.getType(t.getNodeType(this)),s=t.bufferCount,o=s>0&&"buffer"===r.type?", "+s:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(r))i.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${l}> ${r.name} : ${n};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${n}>`:`${n}`}${o} >`;i.push(this._getWGSLStructBinding(r.name,e,l,a.binding++,a.group))}}else{const e=this.getType(this.getVectorType(r.type)),t=r.groupNode.name;(s[t]||(s[t]={index:a.binding++,id:a.group,snippets:[]})).snippets.push(`\t${r.name} : ${e}`)}}for(const e in s){const t=s[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let a=n.join("\n");return a+=i.join("\n"),a+=r.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const n=e[t];n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.structs=this.getStructs(t),n.vars=this.getVars(t),n.codes=this.getCodes(t),n.directives=this.getDirectives(t),n.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],s=r[r.length-1],a=s.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),l=e.name;if(l&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${l}\n`),i+=`${r.code}\n\t`,e===s&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.Vertex = ${r.result};`;else if("fragment"===t)if(o)n.returnType=a.getNodeType(this),n.structs+="var output : "+n.returnType+";",i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),n.returnType="OutputStruct",n.structs+=this._getWGSLStruct("OutputStruct",e),n.structs+="\nvar output : OutputStruct;",i+=`output.color = ${r.result};\n\n\treturn output;`}}n.flow=i}this.shaderStage=null,null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let n;return null!==t&&(n=this._getWGSLMethod(e+"_"+t)),void 0===n&&(n=this._getWGSLMethod(e)),n||e}getType(e){return oN[e]||e}isAvailable(e){let t=sN[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),sN[e]=t),t}_getWGSLMethod(e){return void 0!==uN[e]&&this._include(e),cN[e]}_include(e){const t=uN[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${hN}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${t}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,n,i=0,r=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${n}> ${e} : ${s};`}}class pN{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=zR.Depth24PlusStencil8:e.depth&&(t=zR.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,n=e.getRenderTarget();t=n?n.samples:e.samples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const n=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:n?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?vR:e.isLineSegments||e.isMesh&&!0===t.wireframe?yR:e.isLine?xR:e.isMesh?bR:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===ne)return zR.BGRA8Unorm;if(e===ue)return zR.RGBA16Float;throw new Error("Unsupported outputType")}}const fN=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]),mN=new Map([[Xi,["float16"]]]),gN=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class _N{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),i=this.backend,r=i.get(n);let s=r.buffer;if(void 0===s){const a=i.device;let o=n.array;if(!1===e.normalized)if(o.constructor===Int16Array)o=new Int32Array(o);else if(o.constructor===Uint16Array&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e1&&(i.multisampled=!0,n.texture.isDepthTexture||(i.sampleType=wC)),n.texture.isDepthTexture)i.sampleType=AC;else if(n.texture.isDataTexture||n.texture.isDataArrayTexture||n.texture.isData3DTexture){const e=n.texture.type;e===ae?i.sampleType=RC:e===oe?i.sampleType=CC:e===le&&(this.backend.hasFeature("float32-filterable")?i.sampleType=EC:i.sampleType=wC)}n.isSampledCubeTexture?i.viewDimension=LC:n.texture.isDataArrayTexture||n.texture.isCompressedArrayTexture?i.viewDimension=UC:n.isSampledTexture3D&&(i.viewDimension=IC),e.texture=i}else console.error(`WebGPUBindingUtils: Unsupported binding "${n}".`);i.push(e)}return n.createBindGroupLayout({entries:i})}createBindings(e,t,n,i=0){const{backend:r,bindGroupLayoutCache:s}=this,a=r.get(e);let o,l=s.get(e.bindingsReference);void 0===l&&(l=this.createBindingsLayout(e),s.set(e.bindingsReference,l)),n>0&&(void 0===a.groups&&(a.groups=[],a.versions=[]),a.versions[n]===i&&(o=a.groups[n])),void 0===o&&(o=this.createBindGroup(e,l),n>0&&(a.groups[n]=o,a.versions[n]=i)),a.group=o,a.layout=l}updateBinding(e){const t=this.backend,n=t.device,i=e.buffer,r=t.get(e).buffer;n.queue.writeBuffer(r,0,i,0)}createBindGroupIndex(e,t){const n=this.backend.device,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0],s=n.createBuffer({label:"bindingCameraIndex_"+r,size:16,usage:i});n.queue.writeBuffer(s,0,e,0);const a=[{binding:0,resource:{buffer:s}}];return n.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:a})}createBindGroup(e,t){const n=this.backend,i=n.device;let r=0;const s=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=n.get(t);if(void 0===e.buffer){const n=t.byteLength,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,s=i.createBuffer({label:"bindingBuffer_"+t.name,size:n,usage:r});e.buffer=s}s.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=n.get(t);if(void 0===e.buffer){const i=t.attribute;e.buffer=n.get(i).buffer}s.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isSampler){const e=n.get(t.texture);s.push({binding:r,resource:e.sampler})}else if(t.isSampledTexture){const e=n.get(t.texture);let a;if(void 0!==e.externalTexture)a=i.importExternalTexture({source:e.externalTexture});else{const n=t.store?1:e.texture.mipLevelCount,i=`view-${e.texture.width}-${e.texture.height}-${n}`;if(a=e[i],void 0===a){const r=OC;let s;s=t.isSampledCubeTexture?LC:t.isSampledTexture3D?IC:t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?UC:DC,a=e[i]=e.texture.createView({aspect:r,dimension:s,mipLevelCount:n})}}s.push({binding:r,resource:a})}r++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:s})}}class yN{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:n,material:i,geometry:r,pipeline:s}=e,{vertexProgram:a,fragmentProgram:o}=s,l=this.backend,u=l.device,c=l.utils,h=l.get(s),d=[];for(const t of e.getBindings()){const e=l.get(t);d.push(e.layout)}const p=l.attributeUtils.createShaderVertexBuffers(e);let f;!0===i.transparent&&0!==i.blending&&(f=this._getBlending(i));let m={};!0===i.stencilWrite&&(m={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const g=this._getColorWriteMask(i),_=[];if(null!==e.context.textures){const t=e.context.textures;for(let e=0;e1},layout:u.createPipelineLayout({bindGroupLayouts:d})},E={},w=e.context.depth,A=e.context.stencil;if(!0!==w&&!0!==A||(!0===w&&(E.format=S,E.depthWriteEnabled=i.depthWrite,E.depthCompare=b),!0===A&&(E.stencilFront=m,E.stencilBack={},E.stencilReadMask=i.stencilFuncMask,E.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(E.depthBias=i.polygonOffsetUnits,E.depthBiasSlopeScale=i.polygonOffsetFactor,E.depthBiasClamp=0),M.depthStencil=E),null===t)h.pipeline=u.createRenderPipeline(M);else{const e=new Promise((e=>{u.createRenderPipelineAsync(M).then((t=>{h.pipeline=t,e()}))}));t.push(e)}}createBundleEncoder(e){const t=this.backend,{utils:n,device:i}=t,r=n.getCurrentDepthStencilFormat(e),s={label:"renderBundleEncoder",colorFormats:[n.getCurrentColorFormat(e)],depthStencilFormat:r,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(s)}createComputePipeline(e,t){const n=this.backend,i=n.device,r=n.get(e.computeProgram).module,s=n.get(e),a=[];for(const e of t){const t=n.get(e);a.push(t.layout)}s.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,n;const i=e.blending,r=e.blendSrc,s=e.blendDst,a=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,o=null!==e.blendDstAlpha?e.blendDstAlpha:s,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(s),operation:this._getBlendOperation(a)},n={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(l)}}else{const r=(e,i,r,s)=>{t={srcFactor:e,dstFactor:i,operation:sC},n={srcFactor:r,dstFactor:s,operation:sC}};if(e.premultipliedAlpha)switch(i){case 1:r(qR,ZR,qR,ZR);break;case 2:r(qR,qR,qR,qR);break;case 3:r(XR,YR,XR,qR);break;case 4:r(XR,$R,XR,KR)}else switch(i){case 1:r(KR,ZR,qR,ZR);break;case 2:r(KR,qR,KR,qR);break;case 3:r(XR,YR,XR,qR);break;case 4:r(XR,$R,XR,$R)}}if(void 0!==t&&void 0!==n)return{color:t,alpha:n};console.error("THREE.WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case 200:t=XR;break;case 201:t=qR;break;case 202:t=$R;break;case 203:t=YR;break;case T:t=KR;break;case M:t=ZR;break;case 208:t=QR;break;case 209:t=JR;break;case 206:t=eC;break;case 207:t=tC;break;case 210:t=nC;break;case 211:t=iC;break;case 212:t=rC;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case 512:t=TR;break;case 519:t=NR;break;case 513:t=MR;break;case 515:t=wR;break;case 514:t=ER;break;case 518:t=CR;break;case 516:t=AR;break;case 517:t=RR;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case ut:t=dC;break;case 0:t=pC;break;case 7681:t=fC;break;case 5386:t=mC;break;case 7682:t=gC;break;case 7683:t=_C;break;case 34055:t=vC;break;case 34056:t=yC;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case g:t=sC;break;case 101:t=aC;break;case 102:t=oC;break;case 103:t=lC;break;case 104:t=uC;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const i={},r=this.backend.utils;switch(i.topology=r.getPrimitiveTopology(e,n),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?BR:kR),n.side){case 0:i.frontFace=LR,i.cullMode=FR;break;case 1:i.frontFace=LR,i.cullMode=OR;break;case 2:i.frontFace=LR,i.cullMode=IR;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",n.side)}return i}_getColorWriteMask(e){return!0===e.colorWrite?hC:cC}_getDepthCompare(e){let t;if(!1===e.depthTest)t=NR;else{const n=e.depthFunc;switch(n){case 0:t=TR;break;case 1:t=NR;break;case 2:t=MR;break;case 3:t=wR;break;case 4:t=ER;break;case 5:t=CR;break;case 6:t=AR;break;case 7:t=RR;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class xN extends mR{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const i=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Vt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e.id,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,n=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);const r=i.finish();if(this.device.queue.submit([r]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const s=new BigUint64Array(this.resultBuffer.getMappedRange(0,n));let a=0;for(const[,t]of e){const e=s[t],n=s[t+1];a+=Number(n-e)/1e6}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){console.error("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class bN extends QA{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.trackTimestamp=!0===e.trackTimestamp,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new pN(this),this.attributeUtils=new _N(this),this.bindingUtils=new vN(this),this.pipelineUtils=new yN(this),this.textureUtils=new $C(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let n;if(void 0===t.device){const e={powerPreference:t.powerPreference},i="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(kC),s=[];for(const e of r)i.features.has(e)&&s.push(e);const a={requiredFeatures:s,requiredLimits:t.requiredLimits};n=await i.requestDevice(a)}else n=t.device;n.lost.then((t=>{const n={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(n)}));const i=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=n,this.context=i;const r=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(kC.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r}),this.updateSize()}get coordinateSystem(){return St}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(null===e){const t=this.renderer;e={colorAttachments:[{view:null}]},!0!==this.renderer.depth&&!0!==this.renderer.stencil||(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(t.depth,t.stencil).createView()});const n=e.colorAttachments[0];this.renderer.samples>0?n.view=this.colorBuffer.createView():n.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_getRenderPassDescriptor(e,t={}){const n=e.renderTarget,i=this.get(n);let r=i.descriptors;if(void 0===r||i.width!==n.width||i.height!==n.height||i.dimensions!==n.dimensions||i.activeMipmapLevel!==n.activeMipmapLevel||i.activeCubeFace!==e.activeCubeFace||i.samples!==n.samples||i.loadOp!==t.loadOp){r={},i.descriptors=r;const e=()=>{n.removeEventListener("dispose",e),this.delete(n)};n.addEventListener("dispose",e)}const s=e.getCacheKey();let a=r[s];if(void 0===a){const o=e.textures,l=[];let u;for(let i=0;i0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=n.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),s=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:DR}),this.initTimestampQuery(e,s),s.occlusionQuerySet=r;const a=s.depthStencilAttachment;if(null!==e.textures){const t=s.colorAttachments;for(let n=0;n0&&t.currentPass.executeBundles(t.renderBundles),n>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery(),t.currentPass.end(),n>0){const i=8*n;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const s=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,r,0),t.encoder.copyBufferToBuffer(r,0,s,0,i),t.occlusionQueryBuffer=s,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;ea?(l.x=Math.min(t.dispatchCount,a),l.y=Math.ceil(t.dispatchCount/a)):l.x=t.dispatchCount,r.dispatchWorkgroups(l.x,l.y,l.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:n,material:i,context:r,pipeline:s}=e,a=e.getBindings(),o=this.get(r),l=this.get(s).pipeline,u=o.currentSets,c=o.currentPass,h=e.getDrawParameters();if(null===h)return;u.pipeline!==l&&(c.setPipeline(l),u.pipeline=l);const d=u.bindingGroups;for(let e=0,t=a.length;e{if(!0===n.isBatchedMesh){const e=n._multiDrawStarts,i=n._multiDrawCounts,r=n._multiDrawCount,s=n._multiDrawInstances;null!==s&&Vt("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let a=0;a1?0:a;!0===f?c.drawIndexed(i[a],r,e[a]/p.array.BYTES_PER_ELEMENT,0,o):c.draw(i[a],r,e[a],o),t.update(n,i[a],r)}}else if(!0===f){const{vertexCount:i,instanceCount:r,firstVertex:s}=h,a=e.getIndirect();if(null!==a){const e=this.get(a).buffer;c.drawIndexedIndirect(e,0)}else c.drawIndexed(i,r,s,0,0);t.update(n,i,r)}else{const{vertexCount:i,instanceCount:r,firstVertex:s}=h,a=e.getIndirect();if(null!==a){const e=this.get(a).buffer;c.drawIndirect(e,0)}else c.draw(i,r,s,0);t.update(n,i,r)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),i=e.camera.cameras,s=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==i.length){const e=this.get(s),n=[],r=new Uint32Array([0,0,0,0]);for(let t=0,s=i.length;t(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new _R(e)));super(new t(e),e),this.library=new TN,this.isWebGPURenderer=!0}}const EN={type:"change"},wN={type:"start"},AN={type:"end"},RN=1e-6,CN=-1,NN=0,PN=1,DN=2,UN=3,LN=4,IN=new It,ON=new It,FN=new un,BN=new un,kN=new un,zN=new ln,GN=new un,VN=new un,HN=new un,jN=new un;class WN extends ma{constructor(e,t=null){super(e,t),this.enabled=!0,this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=["KeyA","KeyS","KeyD"],this.mouseButtons={LEFT:a,MIDDLE:o,RIGHT:l},this.state=CN,this.keyState=CN,this.target=new un,this._lastPosition=new un,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new un,this._movePrev=new It,this._moveCurr=new It,this._lastAxis=new un,this._zoomStart=new It,this._zoomEnd=new It,this._panStart=new It,this._panEnd=new It,this._pointers=[],this._pointerPositions={},this._onPointerMove=qN.bind(this),this._onPointerDown=XN.bind(this),this._onPointerUp=$N.bind(this),this._onPointerCancel=YN.bind(this),this._onContextMenu=nP.bind(this),this._onMouseWheel=tP.bind(this),this._onKeyDown=ZN.bind(this),this._onKeyUp=KN.bind(this),this._onTouchStart=iP.bind(this),this._onTouchMove=rP.bind(this),this._onTouchEnd=sP.bind(this),this._onMouseDown=QN.bind(this),this._onMouseMove=JN.bind(this),this._onMouseUp=eP.bind(this),this._target0=this.target.clone(),this._position0=this.object.position.clone(),this._up0=this.object.up.clone(),this._zoom0=this.object.zoom,null!==t&&(this.connect(),this.handleResize()),this.update()}connect(){window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){this._eye.subVectors(this.object.position,this.target),this.noRotate||this._rotateCamera(),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this._checkDistances(),this.object.lookAt(this.target),this._lastPosition.distanceToSquared(this.object.position)>RN&&(this.dispatchEvent(EN),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>RN||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(EN),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=CN,this.keyState=CN,this.target.copy(this._target0),this.object.position.copy(this._position0),this.object.up.copy(this._up0),this.object.zoom=this._zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(EN),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(ON.copy(this._panEnd).sub(this._panStart),ON.lengthSq()){if(this.object.isOrthographicCamera){const e=(this.object.right-this.object.left)/this.object.zoom/this.domElement.clientWidth,t=(this.object.top-this.object.bottom)/this.object.zoom/this.domElement.clientWidth;ON.x*=e,ON.y*=t}ON.multiplyScalar(this._eye.length()*this.panSpeed),BN.copy(this._eye).cross(this.object.up).setLength(ON.x),BN.add(FN.copy(this.object.up).setLength(ON.y)),this.object.position.add(BN),this.target.add(BN),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(ON.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){jN.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=jN.length();e?(this._eye.copy(this.object.position).sub(this.target),GN.copy(this._eye).normalize(),VN.copy(this.object.up).normalize(),HN.crossVectors(VN,GN).normalize(),VN.setLength(this._moveCurr.y-this._movePrev.y),HN.setLength(this._moveCurr.x-this._movePrev.x),jN.copy(VN.add(HN)),kN.crossVectors(jN,this._eye).normalize(),e*=this.rotateSpeed,zN.setFromAxisAngle(kN,e),this._eye.applyQuaternion(zN),this.object.up.applyQuaternion(zN),this._lastAxis.copy(kN),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),zN.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(zN),this.object.up.applyQuaternion(zN)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let e;this.state===LN?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=Lt.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(e=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,1!==e&&e>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=Lt.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor)}_getMouseOnScreen(e,t){return IN.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),IN}_getMouseOnCircle(e,t){return IN.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),IN}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;tthis.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()Math.PI&&(n-=pP),i<-Math.PI?i+=pP:i>Math.PI&&(i-=pP),this._spherical.theta=n<=i?Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),!0===this.enableDamping?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let r=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),r=e!=this._spherical.radius}if(dP.setFromSpherical(this._spherical),dP.applyQuaternion(this._quatInverse),t.copy(this.target).add(dP),this.object.lookAt(this.target),!0===this.enableDamping?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let e=null;if(this.object.isPerspectiveCamera){const t=dP.length();e=this._clampDistance(t*this._scale);const n=t-e;this.object.position.addScaledVector(this._dollyDirection,n),this.object.updateMatrixWorld(),r=!!n}else if(this.object.isOrthographicCamera){const t=new un(this._mouse.x,this._mouse.y,0);t.unproject(this.object);const n=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),r=n!==this.object.zoom;const i=new un(this._mouse.x,this._mouse.y,0);i.unproject(this.object),this.object.position.sub(i).add(t),this.object.updateMatrixWorld(),e=dP.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==e&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position):(uP.origin.copy(this.object.position),uP.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(uP.direction))SP||8*(1-this._lastQuaternion.dot(this.object.quaternion))>SP||this._lastTargetPosition.distanceToSquared(this.target)>SP)&&(this.dispatchEvent(aP),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?pP/60*this.autoRotateSpeed*e:pP/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(.01*e);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){dP.setFromMatrixColumn(t,0),dP.multiplyScalar(-e),this._panOffset.add(dP)}_panUp(e,t){!0===this.screenSpacePanning?dP.setFromMatrixColumn(t,1):(dP.setFromMatrixColumn(t,0),dP.crossVectors(this.object.up,dP)),dP.multiplyScalar(e),this._panOffset.add(dP)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;dP.copy(i).sub(this.target);let r=dP.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/n.clientHeight,this.object.matrix),this._panUp(2*t*r/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const n=this.domElement.getBoundingClientRect(),i=e-n.left,r=t-n.top,s=n.width,a=n.height;this._mouse.x=i/s*2-1,this._mouse.y=-r/a*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(pP*this._rotateDelta.x/t.clientHeight),this._rotateUp(pP*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(pP*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-pP*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(pP*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-pP*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(1===this._pointers.length)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateEnd.set(n,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(pP*this._rotateDelta.x/t.clientHeight),this._rotateUp(pP*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const s=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(s,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;tFP||8*(1-this._lastQuaternion.dot(t.quaternion))>FP)&&(this.dispatchEvent(OP),this._lastQuaternion.copy(t.quaternion),this._lastPosition.copy(t.position))}_updateMovementVector(){const e=this._moveState.forward||this.autoForward&&!this._moveState.back?1:0;this._moveVector.x=-this._moveState.left+this._moveState.right,this._moveVector.y=-this._moveState.down+this._moveState.up,this._moveVector.z=-e+this._moveState.back}_updateRotationVector(){this._rotationVector.x=-this._moveState.pitchDown+this._moveState.pitchUp,this._rotationVector.y=-this._moveState.yawRight+this._moveState.yawLeft,this._rotationVector.z=-this._moveState.rollRight+this._moveState.rollLeft}_getContainerDimensions(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}}}function zP(e){if(!e.altKey&&!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this._moveState.forward=1;break;case"KeyS":this._moveState.back=1;break;case"KeyA":this._moveState.left=1;break;case"KeyD":this._moveState.right=1;break;case"KeyR":this._moveState.up=1;break;case"KeyF":this._moveState.down=1;break;case"ArrowUp":this._moveState.pitchUp=1;break;case"ArrowDown":this._moveState.pitchDown=1;break;case"ArrowLeft":this._moveState.yawLeft=1;break;case"ArrowRight":this._moveState.yawRight=1;break;case"KeyQ":this._moveState.rollLeft=1;break;case"KeyE":this._moveState.rollRight=1}this._updateMovementVector(),this._updateRotationVector()}}function GP(e){if(!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this._moveState.forward=0;break;case"KeyS":this._moveState.back=0;break;case"KeyA":this._moveState.left=0;break;case"KeyD":this._moveState.right=0;break;case"KeyR":this._moveState.up=0;break;case"KeyF":this._moveState.down=0;break;case"ArrowUp":this._moveState.pitchUp=0;break;case"ArrowDown":this._moveState.pitchDown=0;break;case"ArrowLeft":this._moveState.yawLeft=0;break;case"ArrowRight":this._moveState.yawRight=0;break;case"KeyQ":this._moveState.rollLeft=0;break;case"KeyE":this._moveState.rollRight=0}this._updateMovementVector(),this._updateRotationVector()}}function VP(e){if(!1!==this.enabled)if(this.dragToLook)this._status++;else{switch(e.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1}this._updateMovementVector()}}function HP(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),n=t.size[0]/2,i=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-n)/n,this._moveState.pitchDown=(e.pageY-t.offset[1]-i)/i,this._updateRotationVector()}}function jP(e){if(!1!==this.enabled){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(e.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0}this._updateMovementVector()}this._updateRotationVector()}}function WP(){!1!==this.enabled&&(this.dragToLook?(this._status=0,this._moveState.yawLeft=this._moveState.pitchDown=0):(this._moveState.forward=0,this._moveState.back=0,this._updateMovementVector()),this._updateRotationVector())}function XP(e){!1!==this.enabled&&e.preventDefault()}const qP={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n\t\tuniform float opacity;\n\n\t\tuniform sampler2D tDiffuse;\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvec4 texel = texture2D( tDiffuse, vUv );\n\t\t\tgl_FragColor = opacity * texel;\n\n\n\t\t}"};class $P{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const YP=new Qs(-1,1,1,-1,0,1);const KP=new class extends tr{constructor(){super(),this.setAttribute("position",new qi([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new qi([0,2,0,0,2,0],2))}};class ZP{constructor(e){this._mesh=new pr(KP,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,YP)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class QP extends $P{constructor(e,t){super(),this.textureID=void 0!==t?t:"tDiffuse",e instanceof xr?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=yr.clone(e.uniforms),this.material=new xr({name:void 0!==e.name?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this.fsQuad=new ZP(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.texture),this.fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this.fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this.fsQuad.render(e))}dispose(){this.material.dispose(),this.fsQuad.dispose()}}class JP extends $P{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const i=e.getContext(),r=e.state;let s,a;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0),this.inverse?(s=0,a=1):(s=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),r.buffers.stencil.setFunc(i.ALWAYS,s,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(n),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(i.EQUAL,1,4294967295),r.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),r.buffers.stencil.setLocked(!0)}}class eD extends $P{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class tD{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),void 0===t){const n=e.getSize(new It);this._width=n.width,this._height=n.height,(t=new sn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ue})).texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new QP(qP),this.copyPass.material.blending=0,this.clock=new aa}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);-1!==t&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t1?i-1:0),s=1;s=0&&r<1?(o=s,l=a):r>=1&&r<2?(o=a,l=s):r>=2&&r<3?(l=s,u=a):r>=3&&r<4?(l=a,u=s):r>=4&&r<5?(o=a,u=s):r>=5&&r<6&&(o=s,u=a);var c=n-s/2;return i(o+c,l+c,u+c)}var fD={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};var mD=/^#[a-fA-F0-9]{6}$/,gD=/^#[a-fA-F0-9]{8}$/,_D=/^#[a-fA-F0-9]{3}$/,vD=/^#[a-fA-F0-9]{4}$/,yD=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,xD=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,bD=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,SD=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function TD(e){if("string"!=typeof e)throw new cD(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return fD[t]?"#"+fD[t]:e}(e);if(t.match(mD))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(gD)){var n=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:n}}if(t.match(_D))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(vD)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var r=yD.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var s=xD.exec(t.substring(0,50));if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10),alpha:parseFloat(""+s[4])>1?parseFloat(""+s[4])/100:parseFloat(""+s[4])};var a=bD.exec(t);if(a){var o="rgb("+pD(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",l=yD.exec(o);if(!l)throw new cD(4,t,o);return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)}}var u=SD.exec(t.substring(0,50));if(u){var c="rgb("+pD(parseInt(""+u[1],10),parseInt(""+u[2],10)/100,parseInt(""+u[3],10)/100)+")",h=yD.exec(c);if(!h)throw new cD(4,t,c);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+u[4])>1?parseFloat(""+u[4])/100:parseFloat(""+u[4])}}throw new cD(5)}function MD(e){return function(e){var t,n=e.red/255,i=e.green/255,r=e.blue/255,s=Math.max(n,i,r),a=Math.min(n,i,r),o=(s+a)/2;if(s===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var l=s-a,u=o>.5?l/(2-s-a):l/(s+a);switch(s){case n:t=(i-r)/l+(i=1?ND(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new cD(7)}function DD(e){if("object"!=typeof e)throw new cD(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return PD(e);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return ND(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&"number"==typeof e.alpha}(e))return function(e,t,n,i){if("object"==typeof e&&void 0===t&&void 0===n&&void 0===i)return e.alpha>=1?CD(e.hue,e.saturation,e.lightness):"rgba("+pD(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new cD(2)}(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return function(e,t,n){if("object"==typeof e&&void 0===t&&void 0===n)return CD(e.hue,e.saturation,e.lightness);throw new cD(1)}(e);throw new cD(8)}function UD(e,t,n){return function(){var i=n.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):UD(e,t,i)}}function LD(e){return UD(e,e.length,[])}function ID(e,t,n){return Math.max(e,Math.min(t,n))}LD((function(e,t){if("transparent"===t)return t;var n=MD(t);return DD(iD({},n,{hue:n.hue+parseFloat(e)}))})),LD((function(e,t){if("transparent"===t)return t;var n=MD(t);return DD(iD({},n,{lightness:ID(0,1,n.lightness-parseFloat(e))}))})),LD((function(e,t){if("transparent"===t)return t;var n=MD(t);return DD(iD({},n,{saturation:ID(0,1,n.saturation-parseFloat(e))}))})),LD((function(e,t){if("transparent"===t)return t;var n=MD(t);return DD(iD({},n,{lightness:ID(0,1,n.lightness+parseFloat(e))}))}));var OD=LD((function(e,t,n){if("transparent"===t)return n;if("transparent"===n)return t;if(0===e)return n;var i=TD(t),r=iD({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),s=TD(n),a=iD({},s,{alpha:"number"==typeof s.alpha?s.alpha:1}),o=r.alpha-a.alpha,l=2*parseFloat(e)-1,u=((l*o==-1?l:l+o)/(1+l*o)+1)/2,c=1-u;return PD({red:Math.floor(r.red*u+a.red*c),green:Math.floor(r.green*u+a.green*c),blue:Math.floor(r.blue*u+a.blue*c),alpha:r.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})})),FD=OD;var BD=LD((function(e,t){if("transparent"===t)return t;var n=TD(t);return PD(iD({},n,{alpha:ID(0,1,(100*("number"==typeof n.alpha?n.alpha:1)+100*parseFloat(e))/100)}))})),kD=BD;LD((function(e,t){if("transparent"===t)return t;var n=MD(t);return DD(iD({},n,{saturation:ID(0,1,n.saturation+parseFloat(e))}))})),LD((function(e,t){return"transparent"===t?t:DD(iD({},MD(t),{hue:parseFloat(e)}))})),LD((function(e,t){return"transparent"===t?t:DD(iD({},MD(t),{lightness:parseFloat(e)}))})),LD((function(e,t){return"transparent"===t?t:DD(iD({},MD(t),{saturation:parseFloat(e)}))})),LD((function(e,t){return"transparent"===t?t:FD(parseFloat(e),"rgb(0, 0, 0)",t)})),LD((function(e,t){return"transparent"===t?t:FD(parseFloat(e),"rgb(255, 255, 255)",t)})),LD((function(e,t){if("transparent"===t)return t;var n=TD(t);return PD(iD({},n,{alpha:ID(0,1,+(100*("number"==typeof n.alpha?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))}));var zD=Object.freeze({Linear:Object.freeze({None:function(e){return e},In:function(e){return e},Out:function(e){return e},InOut:function(e){return e}}),Quadratic:Object.freeze({In:function(e){return e*e},Out:function(e){return e*(2-e)},InOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)}}),Cubic:Object.freeze({In:function(e){return e*e*e},Out:function(e){return--e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)}}),Quartic:Object.freeze({In:function(e){return e*e*e*e},Out:function(e){return 1- --e*e*e*e},InOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)}}),Quintic:Object.freeze({In:function(e){return e*e*e*e*e},Out:function(e){return--e*e*e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)}}),Sinusoidal:Object.freeze({In:function(e){return 1-Math.sin((1-e)*Math.PI/2)},Out:function(e){return Math.sin(e*Math.PI/2)},InOut:function(e){return.5*(1-Math.sin(Math.PI*(.5-e)))}}),Exponential:Object.freeze({In:function(e){return 0===e?0:Math.pow(1024,e-1)},Out:function(e){return 1===e?1:1-Math.pow(2,-10*e)},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?.5*Math.pow(1024,e-1):.5*(2-Math.pow(2,-10*(e-1)))}}),Circular:Object.freeze({In:function(e){return 1-Math.sqrt(1-e*e)},Out:function(e){return Math.sqrt(1- --e*e)},InOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)}}),Elastic:Object.freeze({In:function(e){return 0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)},Out:function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(5*(e-.1)*Math.PI)+1},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?-.5*Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI):.5*Math.pow(2,-10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)+1}}),Back:Object.freeze({In:function(e){var t=1.70158;return 1===e?1:e*e*((t+1)*e-t)},Out:function(e){var t=1.70158;return 0===e?0:--e*e*((t+1)*e+t)+1},InOut:function(e){var t=2.5949095;return(e*=2)<1?e*e*((t+1)*e-t)*.5:.5*((e-=2)*e*((t+1)*e+t)+2)}}),Bounce:Object.freeze({In:function(e){return 1-zD.Bounce.Out(1-e)},Out:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},InOut:function(e){return e<.5?.5*zD.Bounce.In(2*e):.5*zD.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),GD=function(){return performance.now()},VD=function(){function e(){for(var e=[],t=0;t0;){this._tweensAddedDuringUpdate={};for(var i=0;i1?s(e[n],e[n-1],n-i):s(e[r],e[r+1>n?n:r+1],i-r)},Utils:{Linear:function(e,t,n){return(t-e)*n+e}}},jD=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),WD=new VD,XD=function(){function e(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=zD.Linear.None,this._interpolationFunction=HD.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=jD.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,"object"==typeof t?(this._group=t,t.add(this)):!0===t&&(this._group=WD,WD.add(this))}return e.prototype.getId=function(){return this._id},e.prototype.isPlaying=function(){return this._isPlaying},e.prototype.isPaused=function(){return this._isPaused},e.prototype.getDuration=function(){return this._duration},e.prototype.to=function(e,t){if(void 0===t&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},e.prototype.duration=function(e){return void 0===e&&(e=1e3),this._duration=e<0?0:e,this},e.prototype.dynamic=function(e){return void 0===e&&(e=!1),this._isDynamic=e,this},e.prototype.start=function(e,t){if(void 0===e&&(e=GD()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var n in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var r in this._valuesEnd)i[r]=this._valuesEnd[r];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},e.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},e.prototype._setupProperties=function(e,t,n,i,r){for(var s in n){var a=e[s],o=Array.isArray(a),l=o?"array":typeof a,u=!o&&Array.isArray(n[s]);if("undefined"!==l&&"function"!==l){if(u){if(0===(g=n[s]).length)continue;for(var c=[a],h=0,d=g.length;hl)return 1;var e=Math.trunc(a/o),t=a-e*o,n=Math.min(t/s._duration,1);return 0===n&&a===s._duration?1:n}(),c=this._easingFunction(u);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,c),this._onUpdateCallback&&this._onUpdateCallback(this._object,u),0===this._duration||a>=this._duration){if(this._repeat>0){var h=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(r in isFinite(this._repeat)&&(this._repeat-=h),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[r]||(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*h,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),YD.hasOwnProperty(t)?{space:YD[t],local:e}:e}function ZD(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===$D&&t.documentElement.namespaceURI===$D?t.createElement(e):t.createElementNS(n,e)}}function QD(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function JD(e){var t=KD(e);return(t.local?QD:ZD)(t)}function eU(){}function tU(e){return null==e?eU:function(){return this.querySelector(e)}}function nU(){return[]}function iU(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function rU(e){return function(t){return t.matches(e)}}var sU=Array.prototype.find;function aU(){return this.firstElementChild}var oU=Array.prototype.filter;function lU(){return Array.from(this.children)}function uU(e){return new Array(e.length)}function cU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function hU(e,t,n,i,r,s){for(var a,o=0,l=t.length,u=s.length;ot?1:e>=t?0:NaN}function gU(e){return function(){this.removeAttribute(e)}}function _U(e){return function(){this.removeAttributeNS(e.space,e.local)}}function vU(e,t){return function(){this.setAttribute(e,t)}}function yU(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function xU(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function bU(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function SU(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function TU(e){return function(){this.style.removeProperty(e)}}function MU(e,t,n){return function(){this.style.setProperty(e,t,n)}}function EU(e,t,n){return function(){var i=t.apply(this,arguments);null==i?this.style.removeProperty(e):this.style.setProperty(e,i,n)}}function wU(e){return function(){delete this[e]}}function AU(e,t){return function(){this[e]=t}}function RU(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function CU(e){return e.trim().split(/^|\s+/)}function NU(e){return e.classList||new PU(e)}function PU(e){this._node=e,this._names=CU(e.getAttribute("class")||"")}function DU(e,t){for(var n=NU(e),i=-1,r=t.length;++i=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var eL=[null];function tL(e,t){this._groups=e,this._parents=t}tL.prototype={constructor:tL,select:function(e){"function"!=typeof e&&(e=tU(e));for(var t=this._groups,n=t.length,i=new Array(n),r=0;r=x&&(x=y+1);!(v=g[x])&&++x=0;)(i=r[s])&&(a&&4^i.compareDocumentPosition(a)&&a.parentNode.insertBefore(i,a),a=i);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||(e=mU);for(var n=this._groups,i=n.length,r=new Array(i),s=0;s1?this.each((null==t?TU:"function"==typeof t?EU:MU)(e,t,null==n?"":n)):function(e,t){return e.style.getPropertyValue(t)||SU(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?wU:"function"==typeof t?RU:AU)(e,t)):this.node()[e]},classed:function(e,t){var n=CU(e+"");if(arguments.length<2){for(var i=NU(this.node()),r=-1,s=n.length;++r=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}}))}(e+""),a=s.length;if(!(arguments.length<2)){for(o=t?KU:YU,i=0;io&&aL.sort(uL),e=aL.shift(),o=aL.length,e.__d&&(n=void 0,r=(i=(t=e).__v).__e,s=[],a=[],t.__P&&((n=vL({},i)).__v=i.__v+1,iL.vnode&&iL.vnode(n),LL(t.__P,n,i,t.__n,t.__P.namespaceURI,32&i.__u?[r]:null,s,null==r?TL(i):r,!!(32&i.__u),a),n.__v=i.__v,n.__.__k[n.__i]=n,IL(s,n,a),n.__e!=r&&ML(n)));wL.__r=0}function AL(e,t,n,i,r,s,a,o,l,u,c){var h,d,p,f,m,g,_=i&&i.__k||mL,v=t.length;for(l=RL(n,t,_,l,v),h=0;h0?xL(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):a).__=e,a.__b=e.__b+1,o=null,-1!==(u=a.__i=NL(a,n,l,h))&&(h--,(o=n[u])&&(o.__u|=2)),null==o||null===o.__v?(-1==u&&(r>c?d--:rl?d--:d++,a.__u|=4))):e.__k[s]=null;if(h)for(s=0;s(null==l||2&l.__u?0:1))for(r=n-1,s=n+1;r>=0||s=0){if((l=t[r])&&!(2&l.__u)&&a==l.key&&o===l.type)return r;r--}if(s2&&(a.children=arguments.length>3?nL.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return xL(e,a,i,r,null)}(bL,null,[e]),i||fL,fL,t.namespaceURI,i?null:t.firstChild?nL.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,s),IL(r,e,s)}function VL(e,t,n){var i,r,s,a,o=vL({},e.props);for(s in e.type&&e.type.defaultProps&&(a=e.type.defaultProps),t)"key"==s?i=t[s]:"ref"==s?r=t[s]:o[s]=void 0===t[s]&&void 0!==a?a[s]:t[s];return arguments.length>2&&(o.children=arguments.length>3?nL.call(arguments,2):n),xL(e.type,o,i||e.key,r||e.ref,null)}function HL(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n2&&void 0!==arguments[2]?arguments[2]:{}).style,i=void 0===n?{}:n,r=function(e){return"string"==typeof e?new tL([[document.querySelector(e)]],[document.documentElement]):new tL([[e]],eL)}(!!e&&"object"===qL(e)&&!!e.node&&"function"==typeof e.node?e.node():e);"static"===r.style("position")&&r.style("position","relative"),t.tooltipEl=r.append("div").attr("class","float-tooltip-kap"),Object.entries(i).forEach((function(e){var n=XL(e,2),i=n[0],r=n[1];return t.tooltipEl.style(i,r)})),t.tooltipEl.style("left","-10000px").style("display","none");var s="tooltip-".concat(Math.round(1e12*Math.random()));t.mouseInside=!1,r.on("mousemove.".concat(s),(function(e){t.mouseInside=!0;var n=function(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var i=n.createSVGPoint();return i.x=e.clientX,i.y=e.clientY,[(i=i.matrixTransform(t.getScreenCTM().inverse())).x,i.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}(e),i=r.node(),s=i.offsetWidth,a=i.offsetHeight,o=[null===t.offsetX||void 0===t.offsetX?"-".concat(n[0]/s*100,"%"):"number"==typeof t.offsetX?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,null===t.offsetY||void 0===t.offsetY?a>130&&a-n[1]<100?"calc(-100% - 6px)":"21px":"number"==typeof t.offsetY?t.offsetY<0?"calc(-100% - ".concat(Math.abs(t.offsetY),"px)"):"".concat(t.offsetY,"px"):t.offsetY];t.tooltipEl.style("left",n[0]+"px").style("top",n[1]+"px").style("transform","translate(".concat(o.join(","),")")),t.content&&t.tooltipEl.style("display","inline")})),r.on("mouseover.".concat(s),(function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")})),r.on("mouseout.".concat(s),(function(){t.mouseInside=!1,t.tooltipEl.style("display","none")}))},update:function(e){var t,n;e.tooltipEl.style("display",e.content&&e.mouseInside?"inline":"none"),e.content?e.content instanceof HTMLElement?(e.tooltipEl.text(""),e.tooltipEl.append((function(){return e.content}))):"string"==typeof e.content?e.tooltipEl.html(e.content):!function(e){return sL(VL(e))}(e.content)?(e.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",e.content,e.content.toString())):(e.tooltipEl.text(""),t=e.content,delete(n=e.tooltipEl.node()).__k,GL($L(t),n)):e.tooltipEl.text("")}});function KL(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n0),h=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let f=0;i.toneMapped&&(null!==M&&!0!==M.isXRRenderTarget||(f=x.toneMapping));const m=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=void 0!==m?m.length:0,v=ee.get(i),y=_.state.lights;if(!0===G&&(!0===V||e!==w)){const t=e===w&&i.id===E;ye.setState(i,e,t)}let b=!1;i.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version||v.outputColorSpace!==o||r.isBatchedMesh&&!1===v.batching?b=!0:r.isBatchedMesh||!0!==v.batching?r.isBatchedMesh&&!0===v.batchingColor&&null===r.colorTexture||r.isBatchedMesh&&!1===v.batchingColor&&null!==r.colorTexture||r.isInstancedMesh&&!1===v.instancing?b=!0:r.isInstancedMesh||!0!==v.instancing?r.isSkinnedMesh&&!1===v.skinning?b=!0:r.isSkinnedMesh||!0!==v.skinning?r.isInstancedMesh&&!0===v.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===v.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===v.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===v.instancingMorph&&null!==r.morphTexture||v.envMap!==l||!0===i.fog&&v.fog!==s?b=!0:void 0===v.numClippingPlanes||v.numClippingPlanes===ye.numPlanes&&v.numIntersection===ye.numIntersection?(v.vertexAlphas!==u||v.vertexTangents!==c||v.morphTargets!==h||v.morphNormals!==d||v.morphColors!==p||v.toneMapping!==f||v.morphTargetsCount!==g)&&(b=!0):b=!0:b=!0:b=!0:b=!0:(b=!0,v.__version=i.version);let S=v.currentProgram;!0===b&&(S=Ye(i,t,r));let T=!1,A=!1,R=!1;const C=S.getUniforms(),N=v.uniforms;Q.useProgram(S.program)&&(T=!0,A=!0,R=!0);i.id!==E&&(E=i.id,A=!0);if(T||w!==e){Q.buffers.depth.getReversed()?(H.copy(e.projectionMatrix),function(e){const t=e.elements;t[2]=.5*t[2]+.5*t[3],t[6]=.5*t[6]+.5*t[7],t[10]=.5*t[10]+.5*t[11],t[14]=.5*t[14]+.5*t[15]}(H),function(e){const t=e.elements;-1===t[11]?(t[10]=-t[10]-1,t[14]=-t[14]):(t[10]=-t[10],t[14]=1-t[14])}(H),C.setValue(Pe,"projectionMatrix",H)):C.setValue(Pe,"projectionMatrix",e.projectionMatrix),C.setValue(Pe,"viewMatrix",e.matrixWorldInverse);const t=C.map.cameraPosition;void 0!==t&&t.setValue(Pe,W.setFromMatrixPosition(e.matrixWorld)),Z.logarithmicDepthBuffer&&C.setValue(Pe,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&C.setValue(Pe,"isOrthographic",!0===e.isOrthographicCamera),w!==e&&(w=e,A=!0,R=!0)}if(r.isSkinnedMesh){C.setOptional(Pe,r,"bindMatrix"),C.setOptional(Pe,r,"bindMatrixInverse");const e=r.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),C.setValue(Pe,"boneTexture",e.boneTexture,ie))}r.isBatchedMesh&&(C.setOptional(Pe,r,"batchingTexture"),C.setValue(Pe,"batchingTexture",r._matricesTexture,ie),C.setOptional(Pe,r,"batchingIdTexture"),C.setValue(Pe,"batchingIdTexture",r._indirectTexture,ie),C.setOptional(Pe,r,"batchingColorTexture"),null!==r._colorsTexture&&C.setValue(Pe,"batchingColorTexture",r._colorsTexture,ie));const P=n.morphAttributes;void 0===P.position&&void 0===P.normal&&void 0===P.color||Te.update(r,n,S);(A||v.receiveShadow!==r.receiveShadow)&&(v.receiveShadow=r.receiveShadow,C.setValue(Pe,"receiveShadow",r.receiveShadow));i.isMeshGouraudMaterial&&null!==i.envMap&&(N.envMap.value=l,N.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);i.isMeshStandardMaterial&&null===i.envMap&&null!==t.environment&&(N.envMapIntensity.value=t.environmentIntensity);A&&(C.setValue(Pe,"toneMappingExposure",x.toneMappingExposure),v.needsLights&&(I=R,(D=N).ambientLightColor.needsUpdate=I,D.lightProbe.needsUpdate=I,D.directionalLights.needsUpdate=I,D.directionalLightShadows.needsUpdate=I,D.pointLights.needsUpdate=I,D.pointLightShadows.needsUpdate=I,D.spotLights.needsUpdate=I,D.spotLightShadows.needsUpdate=I,D.rectAreaLights.needsUpdate=I,D.hemisphereLights.needsUpdate=I),s&&!0===i.fog&&ge.refreshFogUniforms(N,s),ge.refreshMaterialUniforms(N,i,L,U,_.state.transmissionRenderTarget[e.id]),ol.upload(Pe,Ke(v),N,ie));var D,I;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(ol.upload(Pe,Ke(v),N,ie),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&C.setValue(Pe,"center",r.center);if(C.setValue(Pe,"modelViewMatrix",r.modelViewMatrix),C.setValue(Pe,"normalMatrix",r.normalMatrix),C.setValue(Pe,"modelMatrix",r.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const e=i.uniformsGroups;for(let t=0,n=e.length;t{function n(){i.forEach((function(e){ee.get(e).currentProgram.isReady()&&i.delete(e)})),0!==i.size?setTimeout(n,10):t(e)}null!==K.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)}))};let ze=null;function Ge(){He.stop()}function Ve(){He.start()}const He=new _a;function je(e,t,n,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)_.pushLight(e),e.castShadow&&_.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||z.intersectsSprite(e)){i&&X.setFromMatrixPosition(e.matrixWorld).applyMatrix4(j);const t=fe.update(e),r=e.material;r.visible&&g.push(e,t,r,n,X.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||z.intersectsObject(e))){const t=fe.update(e),r=e.material;if(i&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),X.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),X.copy(t.boundingSphere.center)),X.applyMatrix4(e.matrixWorld).applyMatrix4(j)),Array.isArray(r)){const i=t.groups;for(let s=0,a=i.length;s0&&qe(r,t,n),s.length>0&&qe(s,t,n),a.length>0&&qe(a,t,n),Q.buffers.depth.setTest(!0),Q.buffers.depth.setMask(!0),Q.buffers.color.setMask(!0),Q.setPolygonOffset(!1)}function Xe(e,t,n,i){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;void 0===_.state.transmissionRenderTarget[i.id]&&(_.state.transmissionRenderTarget[i.id]=new sn(1,1,{generateMipmaps:!0,type:K.has("EXT_color_buffer_half_float")||K.has("EXT_color_buffer_float")?ue:ne,minFilter:te,samples:4,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Xt.workingColorSpace}));const s=_.state.transmissionRenderTarget[i.id],a=i.viewport||A;s.setSize(a.z*x.transmissionResolutionScale,a.w*x.transmissionResolutionScale);const o=x.getRenderTarget();x.setRenderTarget(s),x.getClearColor(N),P=x.getClearAlpha(),P<1&&x.setClearColor(16777215,.5),x.clear(),$&&be.render(n);const l=x.toneMapping;x.toneMapping=0;const u=i.viewport;if(void 0!==i.viewport&&(i.viewport=void 0),_.setupLightsView(i),!0===G&&ye.setGlobalState(x.clippingPlanes,i),qe(e,n,i),ie.updateMultisampleRenderTarget(s),ie.updateRenderTargetMipmap(s),!1===K.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let r=0,s=t.length;r0)for(let t=0,s=n.length;t0&&Xe(i,r,e,t),$&&be.render(e),We(g,e,t);null!==M&&0===T&&(ie.updateMultisampleRenderTarget(M),ie.updateRenderTargetMipmap(M)),!0===e.isScene&&e.onAfterRender(x,e,t),Ce.resetDefaultState(),E=-1,w=null,y.pop(),y.length>0?(_=y[y.length-1],!0===G&&ye.setGlobalState(x.clippingPlanes,_.state.camera)):_=null,v.pop(),g=v.length>0?v[v.length-1]:null},this.getActiveCubeFace=function(){return S},this.getActiveMipmapLevel=function(){return T},this.getRenderTarget=function(){return M},this.setRenderTargetTextures=function(e,t,n){ee.get(e.texture).__webglTexture=t,ee.get(e.depthTexture).__webglTexture=n;const i=ee.get(e);i.__hasExternalTextures=!0,i.__autoAllocateDepthBuffer=void 0===n,i.__autoAllocateDepthBuffer||!0===K.has("WEBGL_multisampled_render_to_texture")&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),i.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(e,t){const n=ee.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t};const Qe=Pe.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){M=e,S=t,T=n;let i=!0,r=null,s=!1,a=!1;if(e){const o=ee.get(e);if(void 0!==o.__useDefaultFramebuffer)Q.bindFramebuffer(Pe.FRAMEBUFFER,null),i=!1;else if(void 0===o.__webglFramebuffer)ie.setupRenderTarget(e);else if(o.__hasExternalTextures)ie.rebindTextures(e,ee.get(e.texture).__webglTexture,ee.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(o.__boundDepthTexture!==t){if(null!==t&&ee.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");ie.setupDepthRenderbuffer(e)}}const l=e.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const u=ee.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(u[t])?u[t][n]:u[t],s=!0):r=e.samples>0&&!1===ie.useMultisampledRTT(e)?ee.get(e).__webglMultisampledFramebuffer:Array.isArray(u)?u[n]:u,A.copy(e.viewport),R.copy(e.scissor),C=e.scissorTest}else A.copy(F).multiplyScalar(L).floor(),R.copy(B).multiplyScalar(L).floor(),C=k;0!==n&&(r=Qe);if(Q.bindFramebuffer(Pe.FRAMEBUFFER,r)&&i&&Q.drawBuffers(e,r),Q.viewport(A),Q.scissor(R),Q.setScissorTest(C),s){const i=ee.get(e.texture);Pe.framebufferTexture2D(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_CUBE_MAP_POSITIVE_X+t,i.__webglTexture,n)}else if(a){const i=ee.get(e.texture),r=t;Pe.framebufferTextureLayer(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,i.__webglTexture,n,r)}else if(null!==e&&0!==n){const t=ee.get(e.texture);Pe.framebufferTexture2D(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_2D,t.__webglTexture,n)}E=-1},this.readRenderTargetPixels=function(e,t,n,i,r,s,a){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=ee.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){Q.bindFramebuffer(Pe.FRAMEBUFFER,o);try{const a=e.texture,o=a.format,l=a.type;if(!Z.textureFormatReadable(o))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!Z.textureTypeReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r&&Pe.readPixels(t,n,i,r,Re.convert(o),Re.convert(l),s)}finally{const e=null!==M?ee.get(M).__webglFramebuffer:null;Q.bindFramebuffer(Pe.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,i,r,s,a){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=ee.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){const a=e.texture,l=a.format,u=a.type;if(!Z.textureFormatReadable(l))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Z.textureTypeReadable(u))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(t>=0&&t<=e.width-i&&n>=0&&n<=e.height-r){Q.bindFramebuffer(Pe.FRAMEBUFFER,o);const e=Pe.createBuffer();Pe.bindBuffer(Pe.PIXEL_PACK_BUFFER,e),Pe.bufferData(Pe.PIXEL_PACK_BUFFER,s.byteLength,Pe.STREAM_READ),Pe.readPixels(t,n,i,r,Re.convert(l),Re.convert(u),0);const a=null!==M?ee.get(M).__webglFramebuffer:null;Q.bindFramebuffer(Pe.FRAMEBUFFER,a);const c=Pe.fenceSync(Pe.SYNC_GPU_COMMANDS_COMPLETE,0);return Pe.flush(),await function(e,t,n){return new Promise((function(i,r){setTimeout((function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:r();break;case e.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:i()}}),n)}))}(Pe,c,4),Pe.bindBuffer(Pe.PIXEL_PACK_BUFFER,e),Pe.getBufferSubData(Pe.PIXEL_PACK_BUFFER,0,s),Pe.deleteBuffer(e),Pe.deleteSync(c),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,n=0){!0!==e.isTexture&&(Vt("WebGLRenderer: copyFramebufferToTexture function signature has changed."),t=arguments[0]||null,e=arguments[1]);const i=Math.pow(2,-n),r=Math.floor(e.image.width*i),s=Math.floor(e.image.height*i),a=null!==t?t.x:0,o=null!==t?t.y:0;ie.setTexture2D(e,0),Pe.copyTexSubImage2D(Pe.TEXTURE_2D,n,0,0,a,o,r,s),Q.unbindTexture()};const Je=Pe.createFramebuffer(),et=Pe.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,i=null,r=0,s=null){let a,o,l,u,c,h,d,p,f;!0!==e.isTexture&&(Vt("WebGLRenderer: copyTextureToTexture function signature has changed."),i=arguments[0]||null,e=arguments[1],t=arguments[2],s=arguments[3]||0,n=null),null===s&&(0!==r?(Vt("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),s=r,r=0):s=0);const m=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)a=n.max.x-n.min.x,o=n.max.y-n.min.y,l=n.isBox3?n.max.z-n.min.z:1,u=n.min.x,c=n.min.y,h=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-r);a=Math.floor(m.width*t),o=Math.floor(m.height*t),l=e.isDataArrayTexture?m.depth:e.isData3DTexture?Math.floor(m.depth*t):1,u=0,c=0,h=0}null!==i?(d=i.x,p=i.y,f=i.z):(d=0,p=0,f=0);const g=Re.convert(t.format),_=Re.convert(t.type);let v;t.isData3DTexture?(ie.setTexture3D(t,0),v=Pe.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(ie.setTexture2DArray(t,0),v=Pe.TEXTURE_2D_ARRAY):(ie.setTexture2D(t,0),v=Pe.TEXTURE_2D),Pe.pixelStorei(Pe.UNPACK_FLIP_Y_WEBGL,t.flipY),Pe.pixelStorei(Pe.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),Pe.pixelStorei(Pe.UNPACK_ALIGNMENT,t.unpackAlignment);const y=Pe.getParameter(Pe.UNPACK_ROW_LENGTH),x=Pe.getParameter(Pe.UNPACK_IMAGE_HEIGHT),b=Pe.getParameter(Pe.UNPACK_SKIP_PIXELS),S=Pe.getParameter(Pe.UNPACK_SKIP_ROWS),T=Pe.getParameter(Pe.UNPACK_SKIP_IMAGES);Pe.pixelStorei(Pe.UNPACK_ROW_LENGTH,m.width),Pe.pixelStorei(Pe.UNPACK_IMAGE_HEIGHT,m.height),Pe.pixelStorei(Pe.UNPACK_SKIP_PIXELS,u),Pe.pixelStorei(Pe.UNPACK_SKIP_ROWS,c),Pe.pixelStorei(Pe.UNPACK_SKIP_IMAGES,h);const M=e.isDataArrayTexture||e.isData3DTexture,E=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=ee.get(e),i=ee.get(t),m=ee.get(n.__renderTarget),g=ee.get(i.__renderTarget);Q.bindFramebuffer(Pe.READ_FRAMEBUFFER,m.__webglFramebuffer),Q.bindFramebuffer(Pe.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10,i=arguments.length,r=new Array(i>3?i-3:0),s=3;s2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:10,r=e.camera;if(t){var s=new tI.Vector3(0,0,0),a=2*Math.max.apply(Math,JL(Object.entries(t).map((function(e){var t=QL(e,2),n=t[0],i=t[1];return Math.max.apply(Math,JL(i.map((function(e){return Math.abs(s[n]-e)}))))})))),o=(1-2*i/e.height)*r.fov,l=a/Math.atan(o*Math.PI/180),u=l/r.aspect,c=Math.max(l,u);if(c>0){var h=s.clone().sub(r.position).normalize().multiplyScalar(-c);this.cameraPosition(h,s,n)}}return this},getBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0},n=new tI.Box3(new tI.Vector3(0,0,0),new tI.Vector3(0,0,0)),i=e.objects.filter(t);return i.length?(i.forEach((function(e){return n.expandByObject(e)})),Object.assign.apply(Object,JL(["x","y","z"].map((function(e){return ZL({},e,[n.min[e],n.max[e]])}))))):null},getScreenCoords:function(e,t,n,i){var r=new tI.Vector3(t,n,i);return r.project(this.camera()),{x:(r.x+1)*e.width/2,y:-(r.y-1)*e.height/2}},getSceneCoords:function(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=new tI.Vector2(t/e.width*2-1,-n/e.height*2+1),s=new tI.Raycaster;return s.setFromCamera(r,e.camera),Object.assign({},s.ray.at(i,new tI.Vector3))},intersectingObjects:function(e,t,n){var i=new tI.Vector2(t/e.width*2-1,-n/e.height*2+1),r=new tI.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,r.params.Points.threshold=e.pointsHoverPrecision,r.setFromCamera(i,e.camera),r.intersectObjects(e.objects,!0)},renderer:function(e){return e.renderer},scene:function(e){return e.scene},camera:function(e){return e.camera},postProcessingComposer:function(e){return e.postProcessingComposer},controls:function(e){return e.controls},tbControls:function(e){return e.controls}},stateInit:function(){return{scene:new tI.Scene,camera:new tI.PerspectiveCamera,clock:new tI.Clock,tweenGroup:new VD}},init:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=n.controlType,r=void 0===i?"trackball":i,s=n.useWebGPU,a=void 0!==s&&s,o=n.rendererConfig,l=void 0===o?{}:o,u=n.extraRenderers,c=void 0===u?[]:u,h=n.waitForLoadComplete,d=void 0===h||h;e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[r]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new YL(t.container),t.pointerPos=new tI.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach((function(e){return t.container.addEventListener(e,(function(n){if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===n.type&&(n.pressure>0||t.isPointerPressed)&&("touch"!==n.pointerType||void 0===n.movementX||[n.movementX,n.movementY].some((function(e){return Math.abs(e)>1})))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var i=(r=t.container,s=r.getBoundingClientRect(),a=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,{top:s.top+o,left:s.left+a});t.pointerPos.x=n.pageX-i.left,t.pointerPos.y=n.pageY-i.top}var r,s,a,o}),{passive:!0})})),t.container.addEventListener("pointerup",(function(e){t.isPointerPressed=!1,t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag)||requestAnimationFrame((function(){0===e.button&&t.onClick(t.hoverObj||null,e,t.intersection),2===e.button&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersection)}))}),{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",(function(e){t.onRightClick&&e.preventDefault()})),t.renderer=new(a?MN:tI.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},l)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=c,t.extraRenderers.forEach((function(e){e.domElement.style.position="absolute",e.domElement.style.top="0px",e.domElement.style.pointerEvents="none",t.container.appendChild(e.domElement)})),t.postProcessingComposer=new tD(t.renderer),t.postProcessingComposer.addPass(new nD(t.scene,t.camera)),t.controls=new{trackball:WN,orbit:TP,fly:kP}[r](t.camera,t.renderer.domElement),"fly"===r&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==r&&"orbit"!==r||(t.controls.minDistance=.1,t.controls.maxDistance=t.skyRadius,t.controls.addEventListener("start",(function(){t.controlsEngaged=!0})),t.controls.addEventListener("change",(function(){t.controlsEngaged&&(t.controlsDragging=!0)})),t.controls.addEventListener("end",(function(){t.controlsEngaged=!1,t.controlsDragging=!1}))),[t.renderer,t.postProcessingComposer].concat(JL(t.extraRenderers)).forEach((function(e){return e.setSize(t.width,t.height)})),t.camera.aspect=t.width/t.height,t.camera.updateProjectionMatrix(),t.camera.position.z=1e3,t.scene.add(t.skysphere=new tI.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!d,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var n,i=e.width,r=e.height;e.container.style.width="".concat(i,"px"),e.container.style.height="".concat(r,"px"),[e.renderer,e.postProcessingComposer].concat(JL(e.extraRenderers)).forEach((function(e){return e.setSize(i,r)})),e.camera.aspect=i/r;var s=e.viewOffset.slice(0,2);s.some((function(e){return e}))&&(n=e.camera).setViewOffset.apply(n,[i,r].concat(JL(s),[i,r])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var a,o=e.width,l=e.height,u=e.viewOffset.slice(0,2);u.some((function(e){return e}))?(a=e.camera).setViewOffset.apply(a,[o,l].concat(JL(u),[o,l])):e.camera.clearViewOffset()}if(t.hasOwnProperty("skyRadius")&&e.skyRadius&&(e.controls.hasOwnProperty("maxDistance")&&t.skyRadius&&(e.controls.maxDistance=Math.min(e.controls.maxDistance,e.skyRadius)),e.camera.far=2.5*e.skyRadius,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new tI.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=TD(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new tI.Color(kD(1,e.backgroundColor)),c)}function h(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new tI.TextureLoader).load(e.backgroundImageUrl,(function(t){t.colorSpace=tI.SRGBColorSpace,e.skysphere.material=new tI.MeshBasicMaterial({map:t,side:tI.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&h()})):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&h())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach((function(t){return e.scene.remove(t)})),e.lights.forEach((function(t){return e.scene.add(t)}))),t.hasOwnProperty("objects")&&((t.objects||[]).forEach((function(t){return e.scene.remove(t)})),e.objects.forEach((function(t){return e.scene.add(t)})))}});function iI(e,t){var n=new t;return n._destructor&&n._destructor(),{linkProp:function(t){return{default:n[t](),onChange:function(n,i){i[e][t](n)},triggerUpdate:!1}},linkMethod:function(t){return function(n){for(var i=n[e],r=arguments.length,s=new Array(r>1?r-1:0),a=1;a3?r-3:0),a=3;ae.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,l=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){l=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(l)throw a}}}}var u="undefined"==typeof window?null:window,c=u?u.navigator:null;u&&u.document;var d=e(""),h=e({}),p=e((function(){})),f="undefined"==typeof HTMLElement?"undefined":e(HTMLElement),g=function(e){return e&&e.instanceString&&y(e.instanceString)?e.instanceString():null},v=function(t){return null!=t&&e(t)==d},y=function(t){return null!=t&&e(t)===p},m=function(e){return!E(e)&&(Array.isArray?Array.isArray(e):null!=e&&e instanceof Array)},b=function(t){return null!=t&&e(t)===h&&!m(t)&&t.constructor===Object},x=function(t){return null!=t&&e(t)===e(1)&&!isNaN(t)},w=function(e){return"undefined"===f?void 0:null!=e&&e instanceof HTMLElement},E=function(e){return k(e)||C(e)},k=function(e){return"collection"===g(e)&&e._private.single},C=function(e){return"collection"===g(e)&&!e._private.single},S=function(e){return"core"===g(e)},P=function(e){return"stylesheet"===g(e)},D=function(e){return null==e||!(""!==e&&!e.match(/^\s+$/))},T=function(t){return function(t){return null!=t&&e(t)===h}(t)&&y(t.then)},_=function(e,t){t||(t=function(){if(1===arguments.length)return arguments[0];if(0===arguments.length)return"undefined";for(var e=[],t=0;tt?1:0},L=null!=Object.assign?Object.assign.bind(Object):function(e){for(var t=arguments,n=1;n255)return;t.push(Math.floor(a))}var o=r[1]||r[2]||r[3],s=r[1]&&r[2]&&r[3];if(o&&!s)return;var l=n[4];if(void 0!==l){if((l=parseFloat(l))<0||l>1)return;t.push(l)}}return t}(e)||function(e){var t,n,r,i,a,o,s,l;function u(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}var c=new RegExp("^hsl[a]?\\(((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?)))\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%])\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))[%])(?:\\s*,\\s*((?:[-+]?(?:(?:\\d+|\\d*\\.\\d+)(?:[Ee][+-]?\\d+)?))))?\\)$").exec(e);if(c){if((n=parseInt(c[1]))<0?n=(360- -1*n%360)%360:n>360&&(n%=360),n/=360,(r=parseFloat(c[2]))<0||r>100)return;if(r/=100,(i=parseFloat(c[3]))<0||i>100)return;if(i/=100,void 0!==(a=c[4])&&((a=parseFloat(a))<0||a>1))return;if(0===r)o=s=l=Math.round(255*i);else{var d=i<.5?i*(1+r):i+r-i*r,h=2*i-d;o=Math.round(255*u(h,d,n+1/3)),s=Math.round(255*u(h,d,n)),l=Math.round(255*u(h,d,n-1/3))}t=[o,s,l,a]}return t}(e)},R={transparent:[0,0,0,0],aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},V=function(e){for(var t=e.map,n=e.keys,r=n.length,i=0;i=t||n<0||d&&e-u>=a}function v(){var e=H();if(g(e))return y(e);s=setTimeout(v,function(e){var n=t-(e-l);return d?ge(n,a-(e-u)):n}(e))}function y(e){return s=void 0,h&&r?p(e):(r=i=void 0,o)}function m(){var e=H(),n=g(e);if(r=arguments,i=this,l=e,n){if(void 0===s)return f(l);if(d)return clearTimeout(s),s=setTimeout(v,t),p(l)}return void 0===s&&(s=setTimeout(v,t)),o}return t=pe(t)||0,j(n)&&(c=!!n.leading,a=(d="maxWait"in n)?fe(pe(n.maxWait)||0,t):a,h="trailing"in n?!!n.trailing:h),m.cancel=function(){void 0!==s&&clearTimeout(s),u=0,r=l=i=s=void 0},m.flush=function(){return void 0===s?o:y(H())},m},ye=u?u.performance:null,me=ye&&ye.now?function(){return ye.now()}:function(){return Date.now()},be=function(){if(u){if(u.requestAnimationFrame)return function(e){u.requestAnimationFrame(e)};if(u.mozRequestAnimationFrame)return function(e){u.mozRequestAnimationFrame(e)};if(u.webkitRequestAnimationFrame)return function(e){u.webkitRequestAnimationFrame(e)};if(u.msRequestAnimationFrame)return function(e){u.msRequestAnimationFrame(e)}}return function(e){e&&setTimeout((function(){e(me())}),1e3/60)}}(),xe=function(e){return be(e)},we=me,Ee=65599,ke=function(e){for(var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:9261,r=n;!(t=e.next()).done;)r=r*Ee+t.value|0;return r},Ce=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:9261;return t*Ee+e|0},Se=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5381;return(t<<5)+t+e|0},Pe=function(e){return 2097152*e[0]+e[1]},De=function(e,t){return[Ce(e[0],t[0]),Se(e[1],t[1])]},Te=function(e,t){var n={value:0,done:!1},r=0,i=e.length;return ke({next:function(){return r=0&&(e[r]!==t||(e.splice(r,1),!n));r--);},Ge=function(e){e.splice(0,e.length)},Ue=function(e,t,n){return n&&(t=N(n,t)),e[t]},Ze=function(e,t,n,r){n&&(t=N(n,t)),e[t]=r},$e="undefined"!=typeof Map?Map:function(){function e(){t(this,e),this._obj={}}return r(e,[{key:"set",value:function(e,t){return this._obj[e]=t,this}},{key:"delete",value:function(e){return this._obj[e]=void 0,this}},{key:"clear",value:function(){this._obj={}}},{key:"has",value:function(e){return void 0!==this._obj[e]}},{key:"get",value:function(e){return this._obj[e]}}]),e}(),Qe=function(){function e(n){if(t(this,e),this._obj=Object.create(null),this.size=0,null!=n){var r;r=null!=n.instanceString&&n.instanceString()===this.instanceString()?n.toArray():n;for(var i=0;i2&&void 0!==arguments[2])||arguments[2];if(void 0!==e&&void 0!==t&&S(e)){var r=t.group;if(null==r&&(r=t.data&&null!=t.data.source&&null!=t.data.target?"edges":"nodes"),"nodes"===r||"edges"===r){this.length=1,this[0]=this;var i=this._private={cy:e,single:!0,data:t.data||{},position:t.position||{x:0,y:0},autoWidth:void 0,autoHeight:void 0,autoPadding:void 0,compoundBoundsClean:!1,listeners:[],group:r,style:{},rstyle:{},styleCxts:[],styleKeys:{},removed:!0,selected:!!t.selected,selectable:void 0===t.selectable||!!t.selectable,locked:!!t.locked,grabbed:!1,grabbable:void 0===t.grabbable||!!t.grabbable,pannable:void 0===t.pannable?"edges"===r:!!t.pannable,active:!1,classes:new Je,animation:{current:[],queue:[]},rscratch:{},scratch:t.scratch||{},edges:[],children:[],parent:t.parent&&t.parent.isNode()?t.parent:null,traversalCache:{},backgrounding:!1,bbCache:null,bbCacheShift:{x:0,y:0},bodyBounds:null,overlayBounds:null,labelBounds:{all:null,source:null,target:null,main:null},arrowBounds:{source:null,target:null,"mid-source":null,"mid-target":null}};if(null==i.position.x&&(i.position.x=0),null==i.position.y&&(i.position.y=0),t.renderedPosition){var a=t.renderedPosition,o=e.pan(),s=e.zoom();i.position={x:(a.x-o.x)/s,y:(a.y-o.y)/s}}var l=[];m(t.classes)?l=t.classes:v(t.classes)&&(l=t.classes.split(/\s+/));for(var u=0,c=l.length;ut?1:0},u=function(e,t,i,a,o){var s;if(null==i&&(i=0),null==o&&(o=n),i<0)throw new Error("lo must be non-negative");for(null==a&&(a=e.length);in;0<=n?t++:t--)u.push(t);return u}.apply(this).reverse()).length;ag;0<=g?++h:--h)v.push(a(e,r));return v},f=function(e,t,r,i){var a,o,s;for(null==i&&(i=n),a=e[r];r>t&&i(a,o=e[s=r-1>>1])<0;)e[r]=o,r=s;return e[r]=a},g=function(e,t,r){var i,a,o,s,l;for(null==r&&(r=n),a=e.length,l=t,o=e[t],i=2*t+1;i0;){var k=m.pop(),C=g(k),S=k.id();if(d[S]=C,C!==1/0)for(var P=k.neighborhood().intersect(p),D=0;D0)for(n.unshift(t);c[i];){var a=c[i];n.unshift(a.edge),n.unshift(a.node),i=(r=a.node).id()}return o.spawn(n)}}}},ot={kruskal:function(e){e=e||function(e){return 1};for(var t=this.byGroup(),n=t.nodes,r=t.edges,i=n.length,a=new Array(i),o=n,s=function(e){for(var t=0;t0;){if(l=g.pop(),u=l.id(),v.delete(u),w++,u===d){for(var E=[],k=i,C=d,S=m[C];E.unshift(k),null!=S&&E.unshift(S),null!=(k=y[C]);)S=m[C=k.id()];return{found:!0,distance:h[u],path:this.spawn(E),steps:w}}f[u]=!0;for(var P=l._private.edges,D=0;DD&&(p[P]=D,m[P]=S,b[P]=w),!i){var T=S*u+C;!i&&p[T]>D&&(p[T]=D,m[T]=C,b[T]=w)}}}for(var _=0;_1&&void 0!==arguments[1]?arguments[1]:a,r=b(e),i=[],o=r;;){if(null==o)return t.spawn();var l=m(o),u=l.edge,c=l.pred;if(i.unshift(o[0]),o.same(n)&&i.length>0)break;null!=u&&i.unshift(u),o=c}return s.spawn(i)},hasNegativeWeightCycle:f,negativeWeightCycles:g}}},pt=Math.sqrt(2),ft=function(e,t,n){0===n.length&&Ve("Karger-Stein must be run on a connected (sub)graph");for(var r=n[e],i=r[1],a=r[2],o=t[i],s=t[a],l=n,u=l.length-1;u>=0;u--){var c=l[u],d=c[1],h=c[2];(t[d]===o&&t[h]===s||t[d]===s&&t[h]===o)&&l.splice(u,1)}for(var p=0;pr;){var i=Math.floor(Math.random()*t.length);t=ft(i,e,t),n--}return t},vt={kargerStein:function(){var e=this,t=this.byGroup(),n=t.nodes,r=t.edges;r.unmergeBy((function(e){return e.isLoop()}));var i=n.length,a=r.length,o=Math.ceil(Math.pow(Math.log(i)/Math.LN2,2)),s=Math.floor(i/pt);if(!(i<2)){for(var l=[],u=0;u0?1:e<0?-1:0},kt=function(e,t){return Math.sqrt(Ct(e,t))},Ct=function(e,t){var n=t.x-e.x,r=t.y-e.y;return n*n+r*r},St=function(e){for(var t=e.length,n=0,r=0;r=e.x1&&e.y2>=e.y1)return{x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,w:e.x2-e.x1,h:e.y2-e.y1};if(null!=e.w&&null!=e.h&&e.w>=0&&e.h>=0)return{x1:e.x1,y1:e.y1,x2:e.x1+e.w,y2:e.y1+e.h,w:e.w,h:e.h}}},Mt=function(e,t){e.x1=Math.min(e.x1,t.x1),e.x2=Math.max(e.x2,t.x2),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,t.y1),e.y2=Math.max(e.y2,t.y2),e.h=e.y2-e.y1},Bt=function(e,t,n){e.x1=Math.min(e.x1,t),e.x2=Math.max(e.x2,t),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,n),e.y2=Math.max(e.y2,n),e.h=e.y2-e.y1},Nt=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e.x1-=t,e.x2+=t,e.y1-=t,e.y2+=t,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},zt=function(e){var t,n,r,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[0];if(1===o.length)t=n=r=i=o[0];else if(2===o.length)t=r=o[0],i=n=o[1];else if(4===o.length){var s=a(o,4);t=s[0],n=s[1],r=s[2],i=s[3]}return e.x1-=i,e.x2+=n,e.y1-=t,e.y2+=r,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},It=function(e,t){e.x1=t.x1,e.y1=t.y1,e.x2=t.x2,e.y2=t.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1},At=function(e,t){return!(e.x1>t.x2)&&(!(t.x1>e.x2)&&(!(e.x2t.y2)&&!(t.y1>e.y2)))))))},Lt=function(e,t,n){return e.x1<=t&&t<=e.x2&&e.y1<=n&&n<=e.y2},Ot=function(e,t){return Lt(e,t.x1,t.y1)&&Lt(e,t.x2,t.y2)},Rt=function(e,t,n,r,i,a,o){var s,l,u=arguments.length>7&&void 0!==arguments[7]?arguments[7]:"auto",c="auto"===u?nn(i,a):u,d=i/2,h=a/2,p=(c=Math.min(c,d,h))!==d,f=c!==h;if(p){var g=n-d+c-o,v=r-h-o,y=n+d-c+o,m=v;if((s=Zt(e,t,n,r,g,v,y,m,!1)).length>0)return s}if(f){var b=n+d+o,x=r-h+c-o,w=b,E=r+h-c+o;if((s=Zt(e,t,n,r,b,x,w,E,!1)).length>0)return s}if(p){var k=n-d+c-o,C=r+h+o,S=n+d-c+o,P=C;if((s=Zt(e,t,n,r,k,C,S,P,!1)).length>0)return s}if(f){var D=n-d-o,T=r-h+c-o,_=D,M=r+h-c+o;if((s=Zt(e,t,n,r,D,T,_,M,!1)).length>0)return s}var B=n-d+c,N=r-h+c;if((l=Gt(e,t,n,r,B,N,c+o)).length>0&&l[0]<=B&&l[1]<=N)return[l[0],l[1]];var z=n+d-c,I=r-h+c;if((l=Gt(e,t,n,r,z,I,c+o)).length>0&&l[0]>=z&&l[1]<=I)return[l[0],l[1]];var A=n+d-c,L=r+h-c;if((l=Gt(e,t,n,r,A,L,c+o)).length>0&&l[0]>=A&&l[1]>=L)return[l[0],l[1]];var O=n-d+c,R=r+h-c;return(l=Gt(e,t,n,r,O,R,c+o)).length>0&&l[0]<=O&&l[1]>=R?[l[0],l[1]]:[]},Vt=function(e,t,n,r,i,a,o){var s=o,l=Math.min(n,i),u=Math.max(n,i),c=Math.min(r,a),d=Math.max(r,a);return l-s<=e&&e<=u+s&&c-s<=t&&t<=d+s},Ft=function(e,t,n,r,i,a,o,s,l){var u=Math.min(n,o,i)-l,c=Math.max(n,o,i)+l,d=Math.min(r,s,a)-l,h=Math.max(r,s,a)+l;return!(ec||th)},jt=function(e,t,n,r,i,a,o,s){var l=[];!function(e,t,n,r,i){var a,o,s,l,u,c,d,h;0===e&&(e=1e-5),s=-27*(r/=e)+(t/=e)*(9*(n/=e)-t*t*2),a=(o=(3*n-t*t)/9)*o*o+(s/=54)*s,i[1]=0,d=t/3,a>0?(u=(u=s+Math.sqrt(a))<0?-Math.pow(-u,1/3):Math.pow(u,1/3),c=(c=s-Math.sqrt(a))<0?-Math.pow(-c,1/3):Math.pow(c,1/3),i[0]=-d+u+c,d+=(u+c)/2,i[4]=i[2]=-d,d=Math.sqrt(3)*(-c+u)/2,i[3]=d,i[5]=-d):(i[5]=i[3]=0,0===a?(h=s<0?-Math.pow(-s,1/3):Math.pow(s,1/3),i[0]=2*h-d,i[4]=i[2]=-(h+d)):(l=(o=-o)*o*o,l=Math.acos(s/Math.sqrt(l)),h=2*Math.sqrt(o),i[0]=-d+h*Math.cos(l/3),i[2]=-d+h*Math.cos((l+2*Math.PI)/3),i[4]=-d+h*Math.cos((l+4*Math.PI)/3)))}(1*n*n-4*n*i+2*n*o+4*i*i-4*i*o+o*o+r*r-4*r*a+2*r*s+4*a*a-4*a*s+s*s,9*n*i-3*n*n-3*n*o-6*i*i+3*i*o+9*r*a-3*r*r-3*r*s-6*a*a+3*a*s,3*n*n-6*n*i+n*o-n*e+2*i*i+2*i*e-o*e+3*r*r-6*r*a+r*s-r*t+2*a*a+2*a*t-s*t,1*n*i-n*n+n*e-i*e+r*a-r*r+r*t-a*t,l);for(var u=[],c=0;c<6;c+=2)Math.abs(l[c+1])<1e-7&&l[c]>=0&&l[c]<=1&&u.push(l[c]);u.push(1),u.push(0);for(var d,h,p,f=-1,g=0;g=0?pl?(e-i)*(e-i)+(t-a)*(t-a):u-d},Yt=function(e,t,n){for(var r,i,a,o,s=0,l=0;l=e&&e>=a||r<=e&&e<=a))continue;(e-r)/(a-r)*(o-i)+i>t&&s++}return s%2!=0},Xt=function(e,t,n,r,i,a,o,s,l){var u,c=new Array(n.length);null!=s[0]?(u=Math.atan(s[1]/s[0]),s[0]<0?u+=Math.PI/2:u=-u-Math.PI/2):u=s;for(var d,h=Math.cos(-u),p=Math.sin(-u),f=0;f0){var g=Ht(c,-l);d=Wt(g)}else d=c;return Yt(e,t,d)},Wt=function(e){for(var t,n,r,i,a,o,s,l,u=new Array(e.length/2),c=0;c=0&&f<=1&&v.push(f),g>=0&&g<=1&&v.push(g),0===v.length)return[];var y=v[0]*s[0]+e,m=v[0]*s[1]+t;return v.length>1?v[0]==v[1]?[y,m]:[y,m,v[1]*s[0]+e,v[1]*s[1]+t]:[y,m]},Ut=function(e,t,n){return t<=e&&e<=n||n<=e&&e<=t?e:e<=t&&t<=n||n<=t&&t<=e?t:n},Zt=function(e,t,n,r,i,a,o,s,l){var u=e-i,c=n-e,d=o-i,h=t-a,p=r-t,f=s-a,g=d*h-f*u,v=c*h-p*u,y=f*c-d*p;if(0!==y){var m=g/y,b=v/y;return-.001<=m&&m<=1.001&&-.001<=b&&b<=1.001||l?[e+m*c,t+m*p]:[]}return 0===g||0===v?Ut(e,n,o)===o?[o,s]:Ut(e,n,i)===i?[i,a]:Ut(i,o,n)===n?[n,r]:[]:[]},$t=function(e,t,n,r,i,a,o,s){var l,u,c,d,h,p,f=[],g=new Array(n.length),v=!0;if(null==a&&(v=!1),v){for(var y=0;y0){var m=Ht(g,-s);u=Wt(m)}else u=g}else u=n;for(var b=0;bu&&(u=t)},d=function(e){return l[e]},h=0;h0?b.edgesTo(m)[0]:m.edgesTo(b)[0];var w=r(x);m=m.id(),h[m]>h[v]+w&&(h[m]=h[v]+w,p.nodes.indexOf(m)<0?p.push(m):p.updateItem(m),u[m]=0,l[m]=[]),h[m]==h[v]+w&&(u[m]=u[m]+u[v],l[m].push(v))}else for(var E=0;E0;){for(var P=n.pop(),D=0;D0&&o.push(n[s]);0!==o.length&&i.push(r.collection(o))}return i}(c,l,t,r);return b=function(e){for(var t=0;t5&&void 0!==arguments[5]?arguments[5]:Cn,o=r,s=0;s=2?Mn(e,t,n,0,Dn,Tn):Mn(e,t,n,0,Pn)},squaredEuclidean:function(e,t,n){return Mn(e,t,n,0,Dn)},manhattan:function(e,t,n){return Mn(e,t,n,0,Pn)},max:function(e,t,n){return Mn(e,t,n,-1/0,_n)}};function Nn(e,t,n,r,i,a){var o;return o=y(e)?e:Bn[e]||Bn.euclidean,0===t&&y(e)?o(i,a):o(t,n,r,i,a)}Bn["squared-euclidean"]=Bn.squaredEuclidean,Bn.squaredeuclidean=Bn.squaredEuclidean;var zn=He({k:2,m:2,sensitivityThreshold:1e-4,distance:"euclidean",maxIterations:10,attributes:[],testMode:!1,testCentroids:null}),In=function(e){return zn(e)},An=function(e,t,n,r,i){var a="kMedoids"!==i?function(e){return n[e]}:function(e){return r[e](n)},o=n,s=t;return Nn(e,r.length,a,(function(e){return r[e](t)}),o,s)},Ln=function(e,t,n){for(var r=n.length,i=new Array(r),a=new Array(r),o=new Array(t),s=null,l=0;ln)return!1}return!0},jn=function(e,t,n){for(var r=0;ri&&(i=t[l][u],a=u);o[a].push(e[l])}for(var c=0;c=i.threshold||"dendrogram"===i.mode&&1===e.length)return!1;var p,f=t[o],g=t[r[o]];p="dendrogram"===i.mode?{left:f,right:g,key:f.key}:{value:f.value.concat(g.value),key:f.key},e[f.index]=p,e.splice(g.index,1),t[f.key]=p;for(var v=0;vn[g.key][y.key]&&(a=n[g.key][y.key])):"max"===i.linkage?(a=n[f.key][y.key],n[f.key][y.key]1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=!(arguments.length>5&&void 0!==arguments[5])||arguments[5];r?e=e.slice(t,n):(n0&&e.splice(0,t));for(var o=0,s=e.length-1;s>=0;s--){var l=e[s];a?isFinite(l)||(e[s]=-1/0,o++):e.splice(s,1)}i&&e.sort((function(e,t){return e-t}));var u=e.length,c=Math.floor(u/2);return u%2!=0?e[c+1+o]:(e[c-1+o]+e[c+o])/2}(e):"mean"===t?function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=0,i=0,a=t;a1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=1/0,i=t;i1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,r=-1/0,i=t;io&&(a=l,o=t[i*e+l])}a>0&&r.push(a)}for(var u=0;u=D?(T=D,D=M,_=B):M>T&&(T=M);for(var N=0;N0?1:0;C[k%u.minIterations*t+R]=V,O+=V}if(O>0&&(k>=u.minIterations-1||k==u.maxIterations-1)){for(var F=0,j=0;j0&&r.push(i);return r}(t,a,o),X=function(e,t,n){for(var r=rr(e,t,n),i=0;il&&(s=u,l=c)}n[i]=a[s]}return r=rr(e,t,n)}(t,r,Y),W={},H=0;H1)}}));var l=Object.keys(t).filter((function(e){return t[e].cutVertex})).map((function(t){return e.getElementById(t)}));return{cut:e.spawn(l),components:i}},lr=function(){var e=this,t={},n=0,r=[],i=[],a=e.spawn(e);return e.forEach((function(o){if(o.isNode()){var s=o.id();s in t||function o(s){if(i.push(s),t[s]={index:n,low:n++,explored:!1},e.getElementById(s).connectedEdges().intersection(e).forEach((function(e){var n=e.target().id();n!==s&&(n in t||o(n),t[n].explored||(t[s].low=Math.min(t[s].low,t[n].low)))})),t[s].index===t[s].low){for(var l=e.spawn();;){var u=i.pop();if(l.merge(e.getElementById(u)),t[u].low=t[s].index,t[u].explored=!0,u===s)break}var c=l.edgesWith(l),d=l.merge(c);r.push(d),a=a.difference(d)}}(s)}})),{cut:a,components:r}},ur={};[nt,at,ot,lt,ct,ht,vt,sn,un,dn,pn,kn,Kn,Jn,ar,{hierholzer:function(e){if(!b(e)){var t=arguments;e={root:t[0],directed:t[1]}}var n,r,i,a=or(e),o=a.root,s=a.directed,l=this,u=!1;o&&(i=v(o)?this.filter(o)[0].id():o[0].id());var c={},d={};s?l.forEach((function(e){var t=e.id();if(e.isNode()){var i=e.indegree(!0),a=e.outdegree(!0),o=i-a,s=a-i;1==o?n?u=!0:n=t:1==s?r?u=!0:r=t:(s>1||o>1)&&(u=!0),c[t]=[],e.outgoers().forEach((function(e){e.isEdge()&&c[t].push(e.id())}))}else d[t]=[void 0,e.target().id()]})):l.forEach((function(e){var t=e.id();e.isNode()?(e.degree(!0)%2&&(n?r?u=!0:r=t:n=t),c[t]=[],e.connectedEdges().forEach((function(e){return c[t].push(e.id())}))):d[t]=[e.source().id(),e.target().id()]}));var h={found:!1,trail:void 0};if(u)return h;if(r&&n)if(s){if(i&&r!=i)return h;i=r}else{if(i&&r!=i&&n!=i)return h;i||(i=r)}else i||(i=l[0].id());var p=function(e){for(var t,n,r,i=e,a=[e];c[i].length;)t=c[i].shift(),n=d[t][0],i!=(r=d[t][1])?(c[r]=c[r].filter((function(e){return e!=t})),i=r):s||i==n||(c[n]=c[n].filter((function(e){return e!=t})),i=n),a.unshift(t),a.unshift(i);return a},f=[],g=[];for(g=p(i);1!=g.length;)0==c[g[0]].length?(f.unshift(l.getElementById(g.shift())),f.unshift(l.getElementById(g.shift()))):g=p(g.shift()).concat(g);for(var y in f.unshift(l.getElementById(g.shift())),c)if(c[y].length)return h;return h.found=!0,h.trail=this.spawn(f,!0),h}},{hopcroftTarjanBiconnected:sr,htbc:sr,htb:sr,hopcroftTarjanBiconnectedComponents:sr},{tarjanStronglyConnected:lr,tsc:lr,tscc:lr,tarjanStronglyConnectedComponents:lr}].forEach((function(e){L(ur,e)})); +/*! + Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable + Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com) + Licensed under The MIT License (http://opensource.org/licenses/MIT) + */ +var cr=function e(t){if(!(this instanceof e))return new e(t);this.id="Thenable/1.0.7",this.state=0,this.fulfillValue=void 0,this.rejectReason=void 0,this.onFulfilled=[],this.onRejected=[],this.proxy={then:this.then.bind(this)},"function"==typeof t&&t.call(this,this.fulfill.bind(this),this.reject.bind(this))};cr.prototype={fulfill:function(e){return dr(this,1,"fulfillValue",e)},reject:function(e){return dr(this,2,"rejectReason",e)},then:function(e,t){var n=new cr;return this.onFulfilled.push(fr(e,n,"fulfill")),this.onRejected.push(fr(t,n,"reject")),hr(this),n.proxy}};var dr=function(e,t,n,r){return 0===e.state&&(e.state=t,e[n]=r,hr(e)),e},hr=function(e){1===e.state?pr(e,"onFulfilled",e.fulfillValue):2===e.state&&pr(e,"onRejected",e.rejectReason)},pr=function(e,t,n){if(0!==e[t].length){var r=e[t];e[t]=[];var i=function(){for(var e=0;e0:void 0}},clearQueue:function(){return function(){var e=void 0!==this.length?this:[this];if(!(this._private.cy||this).styleEnabled())return this;for(var t=0;t-1};var ri=function(e,t){var n=this.__data__,r=Qr(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this};function ii(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t-1&&e%1==0&&e0&&this.spawn(n).updateStyle().emit("class"),this},addClass:function(e){return this.toggleClass(e,!0)},hasClass:function(e){var t=this[0];return null!=t&&t._private.classes.has(e)},toggleClass:function(e,t){m(e)||(e=e.match(/\S+/g)||[]);for(var n=void 0===t,r=[],i=0,a=this.length;i0&&this.spawn(r).updateStyle().emit("class"),this},removeClass:function(e){return this.toggleClass(e,!1)},flashClass:function(e,t){var n=this;if(null==t)t=250;else if(0===t)return n;return n.addClass(e),setTimeout((function(){n.removeClass(e)}),t),n}};qi.className=qi.classNames=qi.classes;var Yi={metaChar:"[\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\`\\{\\|\\}\\~]",comparatorOp:"=|\\!=|>|>=|<|<=|\\$=|\\^=|\\*=",boolOp:"\\?|\\!|\\^",string:"\"(?:\\\\\"|[^\"])*\"|'(?:\\\\'|[^'])*'",number:I,meta:"degree|indegree|outdegree",separator:"\\s*,\\s*",descendant:"\\s+",child:"\\s+>\\s+",subject:"\\$",group:"node|edge|\\*",directedEdge:"\\s+->\\s+",undirectedEdge:"\\s+<->\\s+"};Yi.variable="(?:[\\w-.]|(?:\\\\"+Yi.metaChar+"))+",Yi.className="(?:[\\w-]|(?:\\\\"+Yi.metaChar+"))+",Yi.value=Yi.string+"|"+Yi.number,Yi.id=Yi.variable,function(){var e,t,n;for(e=Yi.comparatorOp.split("|"),n=0;n=0||"="!==t&&(Yi.comparatorOp+="|\\!"+t)}();var Xi=0,Wi=1,Hi=2,Ki=3,Gi=4,Ui=5,Zi=6,$i=7,Qi=8,Ji=9,ea=10,ta=11,na=12,ra=13,ia=14,aa=15,oa=16,sa=17,la=18,ua=19,ca=20,da=[{selector:":selected",matches:function(e){return e.selected()}},{selector:":unselected",matches:function(e){return!e.selected()}},{selector:":selectable",matches:function(e){return e.selectable()}},{selector:":unselectable",matches:function(e){return!e.selectable()}},{selector:":locked",matches:function(e){return e.locked()}},{selector:":unlocked",matches:function(e){return!e.locked()}},{selector:":visible",matches:function(e){return e.visible()}},{selector:":hidden",matches:function(e){return!e.visible()}},{selector:":transparent",matches:function(e){return e.transparent()}},{selector:":grabbed",matches:function(e){return e.grabbed()}},{selector:":free",matches:function(e){return!e.grabbed()}},{selector:":removed",matches:function(e){return e.removed()}},{selector:":inside",matches:function(e){return!e.removed()}},{selector:":grabbable",matches:function(e){return e.grabbable()}},{selector:":ungrabbable",matches:function(e){return!e.grabbable()}},{selector:":animated",matches:function(e){return e.animated()}},{selector:":unanimated",matches:function(e){return!e.animated()}},{selector:":parent",matches:function(e){return e.isParent()}},{selector:":childless",matches:function(e){return e.isChildless()}},{selector:":child",matches:function(e){return e.isChild()}},{selector:":orphan",matches:function(e){return e.isOrphan()}},{selector:":nonorphan",matches:function(e){return e.isChild()}},{selector:":compound",matches:function(e){return e.isNode()?e.isParent():e.source().isParent()||e.target().isParent()}},{selector:":loop",matches:function(e){return e.isLoop()}},{selector:":simple",matches:function(e){return e.isSimple()}},{selector:":active",matches:function(e){return e.active()}},{selector:":inactive",matches:function(e){return!e.active()}},{selector:":backgrounding",matches:function(e){return e.backgrounding()}},{selector:":nonbackgrounding",matches:function(e){return!e.backgrounding()}}].sort((function(e,t){return function(e,t){return-1*A(e,t)}(e.selector,t.selector)})),ha=function(){for(var e,t={},n=0;n0&&l.edgeCount>0)return je("The selector `"+e+"` is invalid because it uses both a compound selector and an edge selector"),!1;if(l.edgeCount>1)return je("The selector `"+e+"` is invalid because it uses multiple edge selectors"),!1;1===l.edgeCount&&je("The selector `"+e+"` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.")}return!0},toString:function(){if(null!=this.toStringCache)return this.toStringCache;for(var e=function(e){return null==e?"":e},t=function(t){return v(t)?'"'+t+'"':e(t)},n=function(e){return" "+e+" "},r=function(r,a){var o=r.type,s=r.value;switch(o){case Xi:var l=e(s);return l.substring(0,l.length-1);case Ki:var u=r.field,c=r.operator;return"["+u+n(e(c))+t(s)+"]";case Ui:var d=r.operator,h=r.field;return"["+e(d)+h+"]";case Gi:return"["+r.field+"]";case Zi:var p=r.operator;return"[["+r.field+n(e(p))+t(s)+"]]";case $i:return s;case Qi:return"#"+s;case Ji:return"."+s;case sa:case aa:return i(r.parent,a)+n(">")+i(r.child,a);case la:case oa:return i(r.ancestor,a)+" "+i(r.descendant,a);case ua:var f=i(r.left,a),g=i(r.subject,a),v=i(r.right,a);return f+(f.length>0?" ":"")+g+v;case ca:return""}},i=function(e,t){return e.checks.reduce((function(n,i,a){return n+(t===e&&0===a?"$":"")+r(i,t)}),"")},a="",o=0;o1&&o=0&&(t=t.replace("!",""),c=!0),t.indexOf("@")>=0&&(t=t.replace("@",""),u=!0),(o||l||u)&&(i=o||s?""+e:"",a=""+n),u&&(e=i=i.toLowerCase(),n=a=a.toLowerCase()),t){case"*=":r=i.indexOf(a)>=0;break;case"$=":r=i.indexOf(a,i.length-a.length)>=0;break;case"^=":r=0===i.indexOf(a);break;case"=":r=e===n;break;case">":d=!0,r=e>n;break;case">=":d=!0,r=e>=n;break;case"<":d=!0,r=e0;){var u=i.shift();t(u),a.add(u.id()),o&&r(i,a,u)}return e}function Ba(e,t,n){if(n.isParent())for(var r=n._private.children,i=0;i1&&void 0!==arguments[1])||arguments[1];return Ma(this,e,t,Ba)},_a.forEachUp=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ma(this,e,t,Na)},_a.forEachUpAndDown=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return Ma(this,e,t,za)},_a.ancestors=_a.parents,(Pa=Da={data:Fi.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),removeData:Fi.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),scratch:Fi.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:Fi.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),rscratch:Fi.data({field:"rscratch",allowBinding:!1,allowSetting:!0,settingTriggersEvent:!1,allowGetting:!0}),removeRscratch:Fi.removeData({field:"rscratch",triggerEvent:!1}),id:function(){var e=this[0];if(e)return e._private.data.id}}).attr=Pa.data,Pa.removeAttr=Pa.removeData;var Ia,Aa,La=Da,Oa={};function Ra(e){return function(t){if(void 0===t&&(t=!0),0!==this.length&&this.isNode()&&!this.removed()){for(var n=0,r=this[0],i=r._private.edges,a=0;at})),minIndegree:Va("indegree",(function(e,t){return et})),minOutdegree:Va("outdegree",(function(e,t){return et}))}),L(Oa,{totalDegree:function(e){for(var t=0,n=this.nodes(),r=0;r0,c=u;u&&(l=l[0]);var d=c?l.position():{x:0,y:0};return i={x:s.x-d.x,y:s.y-d.y},void 0===e?i:i[e]}for(var h=0;h0,y=g;g&&(f=f[0]);var m=y?f.position():{x:0,y:0};void 0!==t?p.position(e,t+m[e]):void 0!==i&&p.position({x:i.x+m.x,y:i.y+m.y})}}else if(!a)return;return this}}).modelPosition=Ia.point=Ia.position,Ia.modelPositions=Ia.points=Ia.positions,Ia.renderedPoint=Ia.renderedPosition,Ia.relativePoint=Ia.relativePosition;var qa,Ya,Xa=Aa;qa=Ya={},Ya.renderedBoundingBox=function(e){var t=this.boundingBox(e),n=this.cy(),r=n.zoom(),i=n.pan(),a=t.x1*r+i.x,o=t.x2*r+i.x,s=t.y1*r+i.y,l=t.y2*r+i.y;return{x1:a,x2:o,y1:s,y2:l,w:o-a,h:l-s}},Ya.dirtyCompoundBoundsCache=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.cy();return t.styleEnabled()&&t.hasCompoundNodes()?(this.forEachUp((function(t){if(t.isParent()){var n=t._private;n.compoundBoundsClean=!1,n.bbCache=null,e||t.emitAndNotify("bounds")}})),this):this},Ya.updateCompoundBounds=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.cy();if(!t.styleEnabled()||!t.hasCompoundNodes())return this;if(!e&&t.batching())return this;function n(e){if(e.isParent()){var t=e._private,n=e.children(),r="include"===e.pstyle("compound-sizing-wrt-labels").value,i={width:{val:e.pstyle("min-width").pfValue,left:e.pstyle("min-width-bias-left"),right:e.pstyle("min-width-bias-right")},height:{val:e.pstyle("min-height").pfValue,top:e.pstyle("min-height-bias-top"),bottom:e.pstyle("min-height-bias-bottom")}},a=n.boundingBox({includeLabels:r,includeOverlays:!1,useCache:!1}),o=t.position;0!==a.w&&0!==a.h||((a={w:e.pstyle("width").pfValue,h:e.pstyle("height").pfValue}).x1=o.x-a.w/2,a.x2=o.x+a.w/2,a.y1=o.y-a.h/2,a.y2=o.y+a.h/2);var s=i.width.left.value;"px"===i.width.left.units&&i.width.val>0&&(s=100*s/i.width.val);var l=i.width.right.value;"px"===i.width.right.units&&i.width.val>0&&(l=100*l/i.width.val);var u=i.height.top.value;"px"===i.height.top.units&&i.height.val>0&&(u=100*u/i.height.val);var c=i.height.bottom.value;"px"===i.height.bottom.units&&i.height.val>0&&(c=100*c/i.height.val);var d=y(i.width.val-a.w,s,l),h=d.biasDiff,p=d.biasComplementDiff,f=y(i.height.val-a.h,u,c),g=f.biasDiff,v=f.biasComplementDiff;t.autoPadding=function(e,t,n,r){if("%"!==n.units)return"px"===n.units?n.pfValue:0;switch(r){case"width":return e>0?n.pfValue*e:0;case"height":return t>0?n.pfValue*t:0;case"average":return e>0&&t>0?n.pfValue*(e+t)/2:0;case"min":return e>0&&t>0?e>t?n.pfValue*t:n.pfValue*e:0;case"max":return e>0&&t>0?e>t?n.pfValue*e:n.pfValue*t:0;default:return 0}}(a.w,a.h,e.pstyle("padding"),e.pstyle("padding-relative-to").value),t.autoWidth=Math.max(a.w,i.width.val),o.x=(-h+a.x1+a.x2+p)/2,t.autoHeight=Math.max(a.h,i.height.val),o.y=(-g+a.y1+a.y2+v)/2}function y(e,t,n){var r=0,i=0,a=t+n;return e>0&&a>0&&(r=t/a*e,i=n/a*e),{biasDiff:r,biasComplementDiff:i}}}for(var r=0;re.x2?r:e.x2,e.y1=ne.y2?i:e.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1)},Ka=function(e,t){return null==t?e:Ha(e,t.x1,t.y1,t.x2,t.y2)},Ga=function(e,t,n){return Ue(e,t,n)},Ua=function(e,t,n){if(!t.cy().headless()){var r,i,a=t._private,o=a.rstyle,s=o.arrowWidth/2;if("none"!==t.pstyle(n+"-arrow-shape").value){"source"===n?(r=o.srcX,i=o.srcY):"target"===n?(r=o.tgtX,i=o.tgtY):(r=o.midX,i=o.midY);var l=a.arrowBounds=a.arrowBounds||{},u=l[n]=l[n]||{};u.x1=r-s,u.y1=i-s,u.x2=r+s,u.y2=i+s,u.w=u.x2-u.x1,u.h=u.y2-u.y1,Nt(u,1),Ha(e,u.x1,u.y1,u.x2,u.y2)}}},Za=function(e,t,n){if(!t.cy().headless()){var r;r=n?n+"-":"";var i=t._private,a=i.rstyle;if(t.pstyle(r+"label").strValue){var o,s,l,u,c=t.pstyle("text-halign"),d=t.pstyle("text-valign"),h=Ga(a,"labelWidth",n),p=Ga(a,"labelHeight",n),f=Ga(a,"labelX",n),g=Ga(a,"labelY",n),v=t.pstyle(r+"text-margin-x").pfValue,y=t.pstyle(r+"text-margin-y").pfValue,m=t.isEdge(),b=t.pstyle(r+"text-rotation"),x=t.pstyle("text-outline-width").pfValue,w=t.pstyle("text-border-width").pfValue/2,E=t.pstyle("text-background-padding").pfValue,k=p,C=h,S=C/2,P=k/2;if(m)o=f-S,s=f+S,l=g-P,u=g+P;else{switch(c.value){case"left":o=f-C,s=f;break;case"center":o=f-S,s=f+S;break;case"right":o=f,s=f+C}switch(d.value){case"top":l=g-k,u=g;break;case"center":l=g-P,u=g+P;break;case"bottom":l=g,u=g+k}}o+=v-Math.max(x,w)-E-2,s+=v+Math.max(x,w)+E+2,l+=y-Math.max(x,w)-E-2,u+=y+Math.max(x,w)+E+2;var D=n||"main",T=i.labelBounds,_=T[D]=T[D]||{};_.x1=o,_.y1=l,_.x2=s,_.y2=u,_.w=s-o,_.h=u-l;var M=m&&"autorotate"===b.strValue,B=null!=b.pfValue&&0!==b.pfValue;if(M||B){var N=M?Ga(i.rstyle,"labelAngle",n):b.pfValue,z=Math.cos(N),I=Math.sin(N),A=(o+s)/2,L=(l+u)/2;if(!m){switch(c.value){case"left":A=s;break;case"right":A=o}switch(d.value){case"top":L=u;break;case"bottom":L=l}}var O=function(e,t){return{x:(e-=A)*z-(t-=L)*I+A,y:e*I+t*z+L}},R=O(o,l),V=O(o,u),F=O(s,l),j=O(s,u);o=Math.min(R.x,V.x,F.x,j.x),s=Math.max(R.x,V.x,F.x,j.x),l=Math.min(R.y,V.y,F.y,j.y),u=Math.max(R.y,V.y,F.y,j.y)}var q=D+"Rot",Y=T[q]=T[q]||{};Y.x1=o,Y.y1=l,Y.x2=s,Y.y2=u,Y.w=s-o,Y.h=u-l,Ha(e,o,l,s,u),Ha(i.labelBounds.all,o,l,s,u)}return e}},$a=function(e,t){var n,r,i,a,o,s,l,u=e._private.cy,c=u.styleEnabled(),d=u.headless(),h=_t(),p=e._private,f=e.isNode(),g=e.isEdge(),v=p.rstyle,y=f&&c?e.pstyle("bounds-expansion").pfValue:[0],m=function(e){return"none"!==e.pstyle("display").value},b=!c||m(e)&&(!g||m(e.source())&&m(e.target()));if(b){var x=0;c&&t.includeOverlays&&0!==e.pstyle("overlay-opacity").value&&(x=e.pstyle("overlay-padding").value);var w=0;c&&t.includeUnderlays&&0!==e.pstyle("underlay-opacity").value&&(w=e.pstyle("underlay-padding").value);var E=Math.max(x,w),k=0;if(c&&(k=e.pstyle("width").pfValue/2),f&&t.includeNodes){var C=e.position();o=C.x,s=C.y;var S=e.outerWidth()/2,P=e.outerHeight()/2;Ha(h,n=o-S,i=s-P,r=o+S,a=s+P),c&&t.includeOutlines&&function(e,t){if(!t.cy().headless()){var n,r,i,a=t.pstyle("outline-opacity").value,o=t.pstyle("outline-width").value;if(a>0&&o>0){var s=t.pstyle("outline-offset").value,l=t.pstyle("shape").value,u=o+s,c=(e.w+2*u)/e.w,d=(e.h+2*u)/e.h,h=0;["diamond","pentagon","round-triangle"].includes(l)?(c=(e.w+2.4*u)/e.w,h=-u/3.6):["concave-hexagon","rhomboid","right-rhomboid"].includes(l)?c=(e.w+2.4*u)/e.w:"star"===l?(c=(e.w+2.8*u)/e.w,d=(e.h+2.6*u)/e.h,h=-u/3.8):"triangle"===l?(c=(e.w+2.8*u)/e.w,d=(e.h+2.4*u)/e.h,h=-u/1.4):"vee"===l&&(c=(e.w+4.4*u)/e.w,d=(e.h+3.8*u)/e.h,h=.5*-u);var p=e.h*d-e.h,f=e.w*c-e.w;if(zt(e,[Math.ceil(p/2),Math.ceil(f/2)]),0!==h){var g=(r=0,i=h,{x1:(n=e).x1+r,x2:n.x2+r,y1:n.y1+i,y2:n.y2+i,w:n.w,h:n.h});Mt(e,g)}}}}(h,e)}else if(g&&t.includeEdges)if(c&&!d){var D=e.pstyle("curve-style").strValue;if(n=Math.min(v.srcX,v.midX,v.tgtX),r=Math.max(v.srcX,v.midX,v.tgtX),i=Math.min(v.srcY,v.midY,v.tgtY),a=Math.max(v.srcY,v.midY,v.tgtY),Ha(h,n-=k,i-=k,r+=k,a+=k),"haystack"===D){var T=v.haystackPts;if(T&&2===T.length){if(n=T[0].x,i=T[0].y,n>(r=T[1].x)){var _=n;n=r,r=_}if(i>(a=T[1].y)){var M=i;i=a,a=M}Ha(h,n-k,i-k,r+k,a+k)}}else if("bezier"===D||"unbundled-bezier"===D||D.endsWith("segments")||D.endsWith("taxi")){var B;switch(D){case"bezier":case"unbundled-bezier":B=v.bezierPts;break;case"segments":case"taxi":case"round-segments":case"round-taxi":B=v.linePts}if(null!=B)for(var N=0;N(r=A.x)){var L=n;n=r,r=L}if((i=I.y)>(a=A.y)){var O=i;i=a,a=O}Ha(h,n-=k,i-=k,r+=k,a+=k)}if(c&&t.includeEdges&&g&&(Ua(h,e,"mid-source"),Ua(h,e,"mid-target"),Ua(h,e,"source"),Ua(h,e,"target")),c)if("yes"===e.pstyle("ghost").value){var R=e.pstyle("ghost-offset-x").pfValue,V=e.pstyle("ghost-offset-y").pfValue;Ha(h,h.x1+R,h.y1+V,h.x2+R,h.y2+V)}var F=p.bodyBounds=p.bodyBounds||{};It(F,h),zt(F,y),Nt(F,1),c&&(n=h.x1,r=h.x2,i=h.y1,a=h.y2,Ha(h,n-E,i-E,r+E,a+E));var j=p.overlayBounds=p.overlayBounds||{};It(j,h),zt(j,y),Nt(j,1);var q=p.labelBounds=p.labelBounds||{};null!=q.all?((l=q.all).x1=1/0,l.y1=1/0,l.x2=-1/0,l.y2=-1/0,l.w=0,l.h=0):q.all=_t(),c&&t.includeLabels&&(t.includeMainLabels&&Za(h,e,null),g&&(t.includeSourceLabels&&Za(h,e,"source"),t.includeTargetLabels&&Za(h,e,"target")))}return h.x1=Wa(h.x1),h.y1=Wa(h.y1),h.x2=Wa(h.x2),h.y2=Wa(h.y2),h.w=Wa(h.x2-h.x1),h.h=Wa(h.y2-h.y1),h.w>0&&h.h>0&&b&&(zt(h,y),Nt(h,1)),h},Qa=function(e){var t=0,n=function(e){return(e?1:0)<0&&void 0!==arguments[0]?arguments[0]:bo,t=arguments.length>1?arguments[1]:void 0,n=0;n=0;s--)o(s);return this},wo.removeAllListeners=function(){return this.removeListener("*")},wo.emit=wo.trigger=function(e,t,n){var r=this.listeners,i=r.length;return this.emitting++,m(t)||(t=[t]),Co(this,(function(e,a){null!=n&&(r=[{event:a.event,type:a.type,namespace:a.namespace,callback:n}],i=r.length);for(var o=function(n){var i=r[n];if(i.type===a.type&&(!i.namespace||i.namespace===a.namespace||".*"===i.namespace)&&e.eventMatches(e.context,i,a)){var o=[a];null!=t&&function(e,t){for(var n=0;n1&&!r){var i=this.length-1,a=this[i],o=a._private.data.id;this[i]=void 0,this[e]=a,n.set(o,{ele:a,index:e})}return this.length--,this},unmergeOne:function(e){e=e[0];var t=this._private,n=e._private.data.id,r=t.map.get(n);if(!r)return this;var i=r.index;return this.unmergeAt(i),this},unmerge:function(e){var t=this._private.cy;if(!e)return this;if(e&&v(e)){var n=e;e=t.mutableElements().filter(n)}for(var r=0;r=0;t--){e(this[t])&&this.unmergeAt(t)}return this},map:function(e,t){for(var n=[],r=0;rr&&(r=o,n=a)}return{value:r,ele:n}},min:function(e,t){for(var n,r=1/0,i=0;i=0&&i1&&void 0!==arguments[1])||arguments[1],n=this[0],r=n.cy();if(r.styleEnabled()&&n){this.cleanStyle();var i=n._private.style[e];return null!=i?i:t?r.style().getDefaultProperty(e):null}},numericStyle:function(e){var t=this[0];if(t.cy().styleEnabled()&&t){var n=t.pstyle(e);return void 0!==n.pfValue?n.pfValue:n.value}},numericStyleUnits:function(e){var t=this[0];if(t.cy().styleEnabled())return t?t.pstyle(e).units:void 0},renderedStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var n=this[0];return n?t.style().getRenderedStyle(n,e):void 0},style:function(e,t){var n=this.cy();if(!n.styleEnabled())return this;var r=n.style();if(b(e)){var i=e;r.applyBypass(this,i,!1),this.emitAndNotify("style")}else if(v(e)){if(void 0===t){var a=this[0];return a?r.getStylePropertyValue(a,e):void 0}r.applyBypass(this,e,t,!1),this.emitAndNotify("style")}else if(void 0===e){var o=this[0];return o?r.getRawStyle(o):void 0}return this},removeStyle:function(e){var t=this.cy();if(!t.styleEnabled())return this;var n=t.style();if(void 0===e)for(var r=0;r0&&t.push(c[0]),t.push(s[0])}return this.spawn(t,!0).filter(e)}),"neighborhood"),closedNeighborhood:function(e){return this.neighborhood().add(this).filter(e)},openNeighborhood:function(e){return this.neighborhood(e)}}),Go.neighbourhood=Go.neighborhood,Go.closedNeighbourhood=Go.closedNeighborhood,Go.openNeighbourhood=Go.openNeighborhood,L(Go,{source:Ta((function(e){var t,n=this[0];return n&&(t=n._private.source||n.cy().collection()),t&&e?t.filter(e):t}),"source"),target:Ta((function(e){var t,n=this[0];return n&&(t=n._private.target||n.cy().collection()),t&&e?t.filter(e):t}),"target"),sources:Qo({attr:"source"}),targets:Qo({attr:"target"})}),L(Go,{edgesWith:Ta(Jo(),"edgesWith"),edgesTo:Ta(Jo({thisIsSrc:!0}),"edgesTo")}),L(Go,{connectedEdges:Ta((function(e){for(var t=[],n=0;n0);return a},component:function(){var e=this[0];return e.cy().mutableElements().components(e)[0]}}),Go.componentsOf=Go.components;var ts=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(void 0!==e){var i=new $e,a=!1;if(t){if(t.length>0&&b(t[0])&&!k(t[0])){a=!0;for(var o=[],s=new Je,l=0,u=t.length;l0&&void 0!==arguments[0])||arguments[0],r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this,a=i.cy(),o=a._private,s=[],l=[],u=0,c=i.length;u0){for(var R=e.length===i.length?i:new ts(a,e),V=0;V0&&void 0!==arguments[0])||arguments[0],t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],n=this,r=[],i={},a=n._private.cy;function o(e){for(var t=e._private.edges,n=0;n0&&(e?D.emitAndNotify("remove"):t&&D.emit("remove"));for(var T=0;T1e-4&&Math.abs(s.v)>1e-4;);return a?function(e){return u[e*(u.length-1)|0]}:c}}(),as=function(e,t,n,r){var i=function(e,t,n,r){var i=4,a=.001,o=1e-7,s=10,l=11,u=1/(l-1),c="undefined"!=typeof Float32Array;if(4!==arguments.length)return!1;for(var d=0;d<4;++d)if("number"!=typeof arguments[d]||isNaN(arguments[d])||!isFinite(arguments[d]))return!1;e=Math.min(e,1),n=Math.min(n,1),e=Math.max(e,0),n=Math.max(n,0);var h=c?new Float32Array(l):new Array(l);function p(e,t){return 1-3*t+3*e}function f(e,t){return 3*t-6*e}function g(e){return 3*e}function v(e,t,n){return((p(t,n)*e+f(t,n))*e+g(t))*e}function y(e,t,n){return 3*p(t,n)*e*e+2*f(t,n)*e+g(t)}function m(t,r){for(var a=0;a0?i=l:r=l}while(Math.abs(a)>o&&++u=a?m(t,s):0===c?s:x(t,r,r+u)}var E=!1;function k(){E=!0,e===t&&n===r||b()}var C=function(i){return E||k(),e===t&&n===r?i:0===i?0:1===i?1:v(w(i),t,r)};C.getControlPoints=function(){return[{x:e,y:t},{x:n,y:r}]};var S="generateBezier("+[e,t,n,r]+")";return C.toString=function(){return S},C}(e,t,n,r);return function(e,t,n){return e+(t-e)*i(n)}},os={linear:function(e,t,n){return e+(t-e)*n},ease:as(.25,.1,.25,1),"ease-in":as(.42,0,1,1),"ease-out":as(0,0,.58,1),"ease-in-out":as(.42,0,.58,1),"ease-in-sine":as(.47,0,.745,.715),"ease-out-sine":as(.39,.575,.565,1),"ease-in-out-sine":as(.445,.05,.55,.95),"ease-in-quad":as(.55,.085,.68,.53),"ease-out-quad":as(.25,.46,.45,.94),"ease-in-out-quad":as(.455,.03,.515,.955),"ease-in-cubic":as(.55,.055,.675,.19),"ease-out-cubic":as(.215,.61,.355,1),"ease-in-out-cubic":as(.645,.045,.355,1),"ease-in-quart":as(.895,.03,.685,.22),"ease-out-quart":as(.165,.84,.44,1),"ease-in-out-quart":as(.77,0,.175,1),"ease-in-quint":as(.755,.05,.855,.06),"ease-out-quint":as(.23,1,.32,1),"ease-in-out-quint":as(.86,0,.07,1),"ease-in-expo":as(.95,.05,.795,.035),"ease-out-expo":as(.19,1,.22,1),"ease-in-out-expo":as(1,0,0,1),"ease-in-circ":as(.6,.04,.98,.335),"ease-out-circ":as(.075,.82,.165,1),"ease-in-out-circ":as(.785,.135,.15,.86),spring:function(e,t,n){if(0===n)return os.linear;var r=is(e,t,n);return function(e,t,n){return e+(t-e)*r(n)}},"cubic-bezier":as};function ss(e,t,n,r,i){if(1===r)return n;if(t===n)return n;var a=i(t,n,r);return null==e||((e.roundValue||e.color)&&(a=Math.round(a)),void 0!==e.min&&(a=Math.max(a,e.min)),void 0!==e.max&&(a=Math.min(a,e.max))),a}function ls(e,t){return null!=e.pfValue||null!=e.value?null==e.pfValue||null!=t&&"%"===t.type.units?e.value:e.pfValue:e}function us(e,t,n,r,i){var a=null!=i?i.type:null;n<0?n=0:n>1&&(n=1);var o=ls(e,i),s=ls(t,i);if(x(o)&&x(s))return ss(a,o,s,n,r);if(m(o)&&m(s)){for(var l=[],u=0;u0?("spring"===d&&h.push(o.duration),o.easingImpl=os[d].apply(null,h)):o.easingImpl=os[d]}var p,f=o.easingImpl;if(p=0===o.duration?1:(n-l)/o.duration,o.applying&&(p=o.progress),p<0?p=0:p>1&&(p=1),null==o.delay){var g=o.startPosition,y=o.position;if(y&&i&&!e.locked()){var m={};ds(g.x,y.x)&&(m.x=us(g.x,y.x,p,f)),ds(g.y,y.y)&&(m.y=us(g.y,y.y,p,f)),e.position(m)}var b=o.startPan,x=o.pan,w=a.pan,E=null!=x&&r;E&&(ds(b.x,x.x)&&(w.x=us(b.x,x.x,p,f)),ds(b.y,x.y)&&(w.y=us(b.y,x.y,p,f)),e.emit("pan"));var k=o.startZoom,C=o.zoom,S=null!=C&&r;S&&(ds(k,C)&&(a.zoom=Tt(a.minZoom,us(k,C,p,f),a.maxZoom)),e.emit("zoom")),(E||S)&&e.emit("viewport");var P=o.style;if(P&&P.length>0&&i){for(var D=0;D=0;t--){(0,e[t])()}e.splice(0,e.length)},c=a.length-1;c>=0;c--){var d=a[c],h=d._private;h.stopped?(a.splice(c,1),h.hooked=!1,h.playing=!1,h.started=!1,u(h.frames)):(h.playing||h.applying)&&(h.playing&&h.applying&&(h.applying=!1),h.started||hs(0,d,e),cs(t,d,e,n),h.applying&&(h.applying=!1),u(h.frames),null!=h.step&&h.step(e),d.completed()&&(a.splice(c,1),h.hooked=!1,h.playing=!1,h.started=!1,u(h.completes)),s=!0)}return n||0!==a.length||0!==o.length||r.push(t),s}for(var a=!1,o=0;o0?t.notify("draw",n):t.notify("draw")),n.unmerge(r),t.emit("step")}var fs={animate:Fi.animate(),animation:Fi.animation(),animated:Fi.animated(),clearQueue:Fi.clearQueue(),delay:Fi.delay(),delayAnimation:Fi.delayAnimation(),stop:Fi.stop(),addToAnimationPool:function(e){this.styleEnabled()&&this._private.aniEles.merge(e)},stopAnimationLoop:function(){this._private.animationsRunning=!1},startAnimationLoop:function(){var e=this;if(e._private.animationsRunning=!0,e.styleEnabled()){var t=e.renderer();t&&t.beforeRender?t.beforeRender((function(t,n){ps(n,e)}),t.beforeRenderPriorities.animations):function t(){e._private.animationsRunning&&xe((function(n){ps(n,e),t()}))}()}}},gs={qualifierCompare:function(e,t){return null==e||null==t?null==e&&null==t:e.sameText(t)},eventMatches:function(e,t,n){var r=t.qualifier;return null==r||e!==n.target&&k(n.target)&&r.matches(n.target)},addEventFields:function(e,t){t.cy=e,t.target=e},callbackContext:function(e,t,n){return null!=t.qualifier?n.target:e}},vs=function(e){return v(e)?new ka(e):e},ys={createEmitter:function(){var e=this._private;return e.emitter||(e.emitter=new xo(gs,this)),this},emitter:function(){return this._private.emitter},on:function(e,t,n){return this.emitter().on(e,vs(t),n),this},removeListener:function(e,t,n){return this.emitter().removeListener(e,vs(t),n),this},removeAllListeners:function(){return this.emitter().removeAllListeners(),this},one:function(e,t,n){return this.emitter().one(e,vs(t),n),this},once:function(e,t,n){return this.emitter().one(e,vs(t),n),this},emit:function(e,t){return this.emitter().emit(e,t),this},emitAndNotify:function(e,t){return this.emit(e),this.notify(e,t),this}};Fi.eventAliasesOn(ys);var ms={png:function(e){return e=e||{},this._private.renderer.png(e)},jpg:function(e){var t=this._private.renderer;return(e=e||{}).bg=e.bg||"#fff",t.jpg(e)}};ms.jpeg=ms.jpg;var bs={layout:function(e){if(null!=e)if(null!=e.name){var t=e.name,n=this.extension("layout",t);if(null!=n){var r;r=v(e.eles)?this.$(e.eles):null!=e.eles?e.eles:this.$();var i=new n(L({},e,{cy:this,eles:r}));return i}Ve("No such layout `"+t+"` found. Did you forget to import it and `cytoscape.use()` it?")}else Ve("A `name` must be specified to make a layout");else Ve("Layout options must be specified to make a layout")}};bs.createLayout=bs.makeLayout=bs.layout;var xs={notify:function(e,t){var n=this._private;if(this.batching()){n.batchNotifications=n.batchNotifications||{};var r=n.batchNotifications[e]=n.batchNotifications[e]||this.collection();null!=t&&r.merge(t)}else if(n.notificationsEnabled){var i=this.renderer();!this.destroyed()&&i&&i.notify(e,t)}},notifications:function(e){var t=this._private;return void 0===e?t.notificationsEnabled:(t.notificationsEnabled=!!e,this)},noNotifications:function(e){this.notifications(!1),e(),this.notifications(!0)},batching:function(){return this._private.batchCount>0},startBatch:function(){var e=this._private;return null==e.batchCount&&(e.batchCount=0),0===e.batchCount&&(e.batchStyleEles=this.collection(),e.batchNotifications={}),e.batchCount++,this},endBatch:function(){var e=this._private;if(0===e.batchCount)return this;if(e.batchCount--,0===e.batchCount){e.batchStyleEles.updateStyle();var t=this.renderer();Object.keys(e.batchNotifications).forEach((function(n){var r=e.batchNotifications[n];r.empty()?t.notify(n):t.notify(n,r)}))}return this},batch:function(e){return this.startBatch(),e(),this.endBatch(),this},batchData:function(e){var t=this;return this.batch((function(){for(var n=Object.keys(e),r=0;r0;)e.removeChild(e.childNodes[0]);this._private.renderer=null,this.mutableElements().forEach((function(e){var t=e._private;t.rscratch={},t.rstyle={},t.animation.current=[],t.animation.queue=[]}))},onRender:function(e){return this.on("render",e)},offRender:function(e){return this.off("render",e)}};Es.invalidateDimensions=Es.resize;var ks={collection:function(e,t){return v(e)?this.$(e):E(e)?e.collection():m(e)?(t||(t={}),new ts(this,e,t.unique,t.removed)):new ts(this)},nodes:function(e){var t=this.$((function(e){return e.isNode()}));return e?t.filter(e):t},edges:function(e){var t=this.$((function(e){return e.isEdge()}));return e?t.filter(e):t},$:function(e){var t=this._private.elements;return e?t.filter(e):t.spawnSelf()},mutableElements:function(){return this._private.elements}};ks.elements=ks.filter=ks.$;var Cs={};Cs.apply=function(e){for(var t=this._private.cy.collection(),n=0;n0;if(d||c&&h){var p=void 0;d&&h||d?p=l.properties:h&&(p=l.mappedProperties);for(var f=0;f1&&(g=1),s.color){var w=i.valueMin[0],E=i.valueMax[0],k=i.valueMin[1],C=i.valueMax[1],S=i.valueMin[2],P=i.valueMax[2],D=null==i.valueMin[3]?1:i.valueMin[3],T=null==i.valueMax[3]?1:i.valueMax[3],_=[Math.round(w+(E-w)*g),Math.round(k+(C-k)*g),Math.round(S+(P-S)*g),Math.round(D+(T-D)*g)];n={bypass:i.bypass,name:i.name,value:_,strValue:"rgb("+_[0]+", "+_[1]+", "+_[2]+")"}}else{if(!s.number)return!1;var M=i.valueMin+(i.valueMax-i.valueMin)*g;n=this.parse(i.name,M,i.bypass,"mapping")}if(!n)return f(),!1;n.mapping=i,i=n;break;case o.data:for(var B=i.field.split("."),N=d.data,z=0;z0&&a>0){for(var s={},l=!1,u=0;u0?e.delayAnimation(o).play().promise().then(t):t()})).then((function(){return e.animation({style:s,duration:a,easing:e.pstyle("transition-timing-function").value,queue:!1}).play().promise()})).then((function(){n.removeBypasses(e,i),e.emitAndNotify("style"),r.transitioning=!1}))}else r.transitioning&&(this.removeBypasses(e,i),e.emitAndNotify("style"),r.transitioning=!1)},Cs.checkTrigger=function(e,t,n,r,i,a){var o=this.properties[t],s=i(o);null!=s&&s(n,r)&&a(o)},Cs.checkZOrderTrigger=function(e,t,n,r){var i=this;this.checkTrigger(e,t,n,r,(function(e){return e.triggersZOrder}),(function(){i._private.cy.notify("zorder",e)}))},Cs.checkBoundsTrigger=function(e,t,n,r){this.checkTrigger(e,t,n,r,(function(e){return e.triggersBounds}),(function(i){e.dirtyCompoundBoundsCache(),e.dirtyBoundingBoxCache(),!i.triggersBoundsOfParallelBeziers||"curve-style"!==t||"bezier"!==n&&"bezier"!==r||e.parallelEdges().forEach((function(e){e.isBundledBezier()&&e.dirtyBoundingBoxCache()})),!i.triggersBoundsOfConnectedEdges||"display"!==t||"none"!==n&&"none"!==r||e.connectedEdges().forEach((function(e){e.dirtyBoundingBoxCache()}))}))},Cs.checkTriggers=function(e,t,n,r){e.dirtyStyleCache(),this.checkZOrderTrigger(e,t,n,r),this.checkBoundsTrigger(e,t,n,r)};var Ss={applyBypass:function(e,t,n,r){var i=[];if("*"===t||"**"===t){if(void 0!==n)for(var a=0;at.length?i.substr(t.length):""}function o(){n=n.length>r.length?n.substr(r.length):""}for(i=i.replace(/[/][*](\s|.)+?[*][/]/g,"");;){if(i.match(/^\s*$/))break;var s=i.match(/^\s*((?:.|\s)+?)\s*\{((?:.|\s)+?)\}/);if(!s){je("Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: "+i);break}t=s[0];var l=s[1];if("core"!==l)if(new ka(l).invalid){je("Skipping parsing of block: Invalid selector found in string stylesheet: "+l),a();continue}var u=s[2],c=!1;n=u;for(var d=[];;){if(n.match(/^\s*$/))break;var h=n.match(/^\s*(.+?)\s*:\s*(.+?)(?:\s*;|\s*$)/);if(!h){je("Skipping parsing of block: Invalid formatting of style property and value definitions found in:"+u),c=!0;break}r=h[0];var p=h[1],f=h[2];if(this.properties[p])this.parse(p,f)?(d.push({name:p,val:f}),o()):(je("Skipping property: Invalid property definition in: "+r),o());else je("Skipping property: Invalid property name in: "+r),o()}if(c){a();break}this.selector(l);for(var g=0;g=7&&"d"===t[0]&&(l=new RegExp(o.data.regex).exec(t))){if(n)return!1;var d=o.data;return{name:e,value:l,strValue:""+t,mapped:d,field:l[1],bypass:n}}if(t.length>=10&&"m"===t[0]&&(u=new RegExp(o.mapData.regex).exec(t))){if(n)return!1;if(c.multiple)return!1;var h=o.mapData;if(!c.color&&!c.number)return!1;var p=this.parse(e,u[4]);if(!p||p.mapped)return!1;var f=this.parse(e,u[5]);if(!f||f.mapped)return!1;if(p.pfValue===f.pfValue||p.strValue===f.strValue)return je("`"+e+": "+t+"` is not a valid mapper because the output range is zero; converting to `"+e+": "+p.strValue+"`"),this.parse(e,p.strValue);if(c.color){var g=p.value,b=f.value;if(!(g[0]!==b[0]||g[1]!==b[1]||g[2]!==b[2]||g[3]!==b[3]&&(null!=g[3]&&1!==g[3]||null!=b[3]&&1!==b[3])))return!1}return{name:e,value:u,strValue:""+t,mapped:h,field:u[1],fieldMin:parseFloat(u[2]),fieldMax:parseFloat(u[3]),valueMin:p.value,valueMax:f.value,bypass:n}}}if(c.multiple&&"multiple"!==r){var w;if(w=s?t.split(/\s+/):m(t)?t:[t],c.evenMultiple&&w.length%2!=0)return null;for(var E=[],k=[],C=[],S="",P=!1,D=0;D0?" ":"")+T.strValue}return c.validate&&!c.validate(E,k)?null:c.singleEnum&&P?1===E.length&&v(E[0])?{name:e,value:E[0],strValue:E[0],bypass:n}:null:{name:e,value:E,pfValue:C,strValue:S,bypass:n,units:k}}var _,B,N=function(){for(var r=0;rc.max||c.strictMax&&t===c.max))return null;var V={name:e,value:t,strValue:""+t+(z||""),units:z,bypass:n};return c.unitless||"px"!==z&&"em"!==z?V.pfValue=t:V.pfValue="px"!==z&&z?this.getEmSizeInPixels()*t:t,"ms"!==z&&"s"!==z||(V.pfValue="ms"===z?t:1e3*t),"deg"!==z&&"rad"!==z||(V.pfValue="rad"===z?t:(_=t,Math.PI*_/180)),"%"===z&&(V.pfValue=t/100),V}if(c.propList){var F=[],j=""+t;if("none"===j);else{for(var q=j.split(/\s*,\s*|\s+/),Y=0;Y0&&l>0&&!isNaN(n.w)&&!isNaN(n.h)&&n.w>0&&n.h>0)return{zoom:o=(o=(o=Math.min((s-2*t)/n.w,(l-2*t)/n.h))>this._private.maxZoom?this._private.maxZoom:o)=n.minZoom&&(n.maxZoom=t),this},minZoom:function(e){return void 0===e?this._private.minZoom:this.zoomRange({min:e})},maxZoom:function(e){return void 0===e?this._private.maxZoom:this.zoomRange({max:e})},getZoomedViewport:function(e){var t,n,r=this._private,i=r.pan,a=r.zoom,o=!1;if(r.zoomingEnabled||(o=!0),x(e)?n=e:b(e)&&(n=e.level,null!=e.position?t=yt(e.position,a,i):null!=e.renderedPosition&&(t=e.renderedPosition),null==t||r.panningEnabled||(o=!0)),n=(n=n>r.maxZoom?r.maxZoom:n)t.maxZoom||!t.zoomingEnabled?a=!0:(t.zoom=s,i.push("zoom"))}if(r&&(!a||!e.cancelOnFailedZoom)&&t.panningEnabled){var l=e.pan;x(l.x)&&(t.pan.x=l.x,o=!1),x(l.y)&&(t.pan.y=l.y,o=!1),o||i.push("pan")}return i.length>0&&(i.push("viewport"),this.emit(i.join(" ")),this.notify("viewport")),this},center:function(e){var t=this.getCenterPan(e);return t&&(this._private.pan=t,this.emit("pan viewport"),this.notify("viewport")),this},getCenterPan:function(e,t){if(this._private.panningEnabled){if(v(e)){var n=e;e=this.mutableElements().filter(n)}else E(e)||(e=this.mutableElements());if(0!==e.length){var r=e.boundingBox(),i=this.width(),a=this.height();return{x:(i-(t=void 0===t?this._private.zoom:t)*(r.x1+r.x2))/2,y:(a-t*(r.y1+r.y2))/2}}}},reset:function(){return this._private.panningEnabled&&this._private.zoomingEnabled?(this.viewport({pan:{x:0,y:0},zoom:1}),this):this},invalidateSize:function(){this._private.sizeCache=null},size:function(){var e,t,n=this._private,r=n.container,i=this;return n.sizeCache=n.sizeCache||(r?(e=i.window().getComputedStyle(r),t=function(t){return parseFloat(e.getPropertyValue(t))},{width:r.clientWidth-t("padding-left")-t("padding-right"),height:r.clientHeight-t("padding-top")-t("padding-bottom")}):{width:1,height:1})},width:function(){return this.size().width},height:function(){return this.size().height},extent:function(){var e=this._private.pan,t=this._private.zoom,n=this.renderedExtent(),r={x1:(n.x1-e.x)/t,x2:(n.x2-e.x)/t,y1:(n.y1-e.y)/t,y2:(n.y2-e.y)/t};return r.w=r.x2-r.x1,r.h=r.y2-r.y1,r},renderedExtent:function(){var e=this.width(),t=this.height();return{x1:0,y1:0,x2:e,y2:t,w:e,h:t}},multiClickDebounceTime:function(e){return e?(this._private.multiClickDebounceTime=e,this):this._private.multiClickDebounceTime}};As.centre=As.center,As.autolockNodes=As.autolock,As.autoungrabifyNodes=As.autoungrabify;var Ls={data:Fi.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeData:Fi.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),scratch:Fi.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:Fi.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0})};Ls.attr=Ls.data,Ls.removeAttr=Ls.removeData;var Os=function(e){var t=this,n=(e=L({},e)).container;n&&!w(n)&&w(n[0])&&(n=n[0]);var r=n?n._cyreg:null;(r=r||{})&&r.cy&&(r.cy.destroy(),r={});var i=r.readies=r.readies||[];n&&(n._cyreg=r),r.cy=t;var a=void 0!==u&&void 0!==n&&!e.headless,o=e;o.layout=L({name:a?"grid":"null"},o.layout),o.renderer=L({name:a?"canvas":"null"},o.renderer);var s=function(e,t,n){return void 0!==t?t:void 0!==n?n:e},l=this._private={container:n,ready:!1,options:o,elements:new ts(this),listeners:[],aniEles:new ts(this),data:o.data||{},scratch:{},layout:null,renderer:null,destroyed:!1,notificationsEnabled:!0,minZoom:1e-50,maxZoom:1e50,zoomingEnabled:s(!0,o.zoomingEnabled),userZoomingEnabled:s(!0,o.userZoomingEnabled),panningEnabled:s(!0,o.panningEnabled),userPanningEnabled:s(!0,o.userPanningEnabled),boxSelectionEnabled:s(!0,o.boxSelectionEnabled),autolock:s(!1,o.autolock,o.autolockNodes),autoungrabify:s(!1,o.autoungrabify,o.autoungrabifyNodes),autounselectify:s(!1,o.autounselectify),styleEnabled:void 0===o.styleEnabled?a:o.styleEnabled,zoom:x(o.zoom)?o.zoom:1,pan:{x:b(o.pan)&&x(o.pan.x)?o.pan.x:0,y:b(o.pan)&&x(o.pan.y)?o.pan.y:0},animation:{current:[],queue:[]},hasCompoundNodes:!1,multiClickDebounceTime:s(250,o.multiClickDebounceTime)};this.createEmitter(),this.selectionType(o.selectionType),this.zoomRange({min:o.minZoom,max:o.maxZoom});l.styleEnabled&&t.setStyle([]);var c=L({},o,o.renderer);t.initRenderer(c);!function(e,t){if(e.some(T))return vr.all(e).then(t);t(e)}([o.style,o.elements],(function(e){var n=e[0],a=e[1];l.styleEnabled&&t.style().append(n),function(e,n,r){t.notifications(!1);var i=t.mutableElements();i.length>0&&i.remove(),null!=e&&(b(e)||m(e))&&t.add(e),t.one("layoutready",(function(e){t.notifications(!0),t.emit(e),t.one("load",n),t.emitAndNotify("load")})).one("layoutstop",(function(){t.one("done",r),t.emit("done")}));var a=L({},t._private.options.layout);a.eles=t.elements(),t.layout(a).run()}(a,(function(){t.startAnimationLoop(),l.ready=!0,y(o.ready)&&t.on("ready",o.ready);for(var e=0;e0,u=_t(n.boundingBox?n.boundingBox:{x1:0,y1:0,w:r.width(),h:r.height()});if(E(n.roots))e=n.roots;else if(m(n.roots)){for(var c=[],d=0;d0;){var N=_.shift(),z=T(N,M);if(z)N.outgoers().filter((function(e){return e.isNode()&&i.has(e)})).forEach(B);else if(null===z){je("Detected double maximal shift for node `"+N.id()+"`. Bailing maximal adjustment due to cycle. Use `options.maximal: true` only on DAGs.");break}}}D();var I=0;if(n.avoidOverlap)for(var L=0;L0&&b[0].length<=3?l/2:0),d=2*Math.PI/b[r].length*i;return 0===r&&1===b[0].length&&(c=1),{x:G+c*Math.cos(d),y:U+c*Math.sin(d)}}return{x:G+(i+1-(a+1)/2)*o,y:(r+1)*s}})),this};var Xs={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,radius:void 0,startAngle:1.5*Math.PI,sweep:void 0,clockwise:!0,sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function Ws(e){this.options=L({},Xs,e)}Ws.prototype.run=function(){var e=this.options,t=e,n=e.cy,r=t.eles,i=void 0!==t.counterclockwise?!t.counterclockwise:t.clockwise,a=r.nodes().not(":parent");t.sort&&(a=a.sort(t.sort));for(var o,s=_t(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:n.width(),h:n.height()}),l=s.x1+s.w/2,u=s.y1+s.h/2,c=(void 0===t.sweep?2*Math.PI-2*Math.PI/a.length:t.sweep)/Math.max(1,a.length-1),d=0,h=0;h1&&t.avoidOverlap){d*=1.75;var v=Math.cos(c)-Math.cos(0),y=Math.sin(c)-Math.sin(0),m=Math.sqrt(d*d/(v*v+y*y));o=Math.max(m,o)}return r.nodes().layoutPositions(this,t,(function(e,n){var r=t.startAngle+n*c*(i?1:-1),a=o*Math.cos(r),s=o*Math.sin(r);return{x:l+a,y:u+s}})),this};var Hs,Ks={fit:!0,padding:30,startAngle:1.5*Math.PI,sweep:void 0,clockwise:!0,equidistant:!1,minNodeSpacing:10,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,height:void 0,width:void 0,spacingFactor:void 0,concentric:function(e){return e.degree()},levelWidth:function(e){return e.maxDegree()/4},animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function Gs(e){this.options=L({},Ks,e)}Gs.prototype.run=function(){for(var e=this.options,t=e,n=void 0!==t.counterclockwise?!t.counterclockwise:t.clockwise,r=e.cy,i=t.eles,a=i.nodes().not(":parent"),o=_t(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:r.width(),h:r.height()}),s=o.x1+o.w/2,l=o.y1+o.h/2,u=[],c=0,d=0;d0)Math.abs(m[0].value-x.value)>=v&&(m=[],y.push(m));m.push(x)}var w=c+t.minNodeSpacing;if(!t.avoidOverlap){var E=y.length>0&&y[0].length>1,k=(Math.min(o.w,o.h)/2-w)/(y.length+E?1:0);w=Math.min(w,k)}for(var C=0,S=0;S1&&t.avoidOverlap){var _=Math.cos(T)-Math.cos(0),M=Math.sin(T)-Math.sin(0),B=Math.sqrt(w*w/(_*_+M*M));C=Math.max(B,C)}P.r=C,C+=w}if(t.equidistant){for(var N=0,z=0,I=0;I=e.numIter)&&(rl(r,e),r.temperature=r.temperature*e.coolingFactor,!(r.temperature=e.animationThreshold&&a(),xe(t)):(gl(r,e),s())}()}else{for(;u;)u=o(l),l++;gl(r,e),s()}return this},Zs.prototype.stop=function(){return this.stopped=!0,this.thread&&this.thread.stop(),this.emit("layoutstop"),this},Zs.prototype.destroy=function(){return this.thread&&this.thread.stop(),this};var $s=function(e,t,n){for(var r=n.eles.edges(),i=n.eles.nodes(),a=_t(n.boundingBox?n.boundingBox:{x1:0,y1:0,w:e.width(),h:e.height()}),o={isCompound:e.hasCompoundNodes(),layoutNodes:[],idToIndex:{},nodeSize:i.size(),graphSet:[],indexToGraph:[],layoutEdges:[],edgeSize:r.size(),temperature:n.initialTemp,clientWidth:a.w,clientHeight:a.h,boundingBox:a},s=n.eles.components(),l={},u=0;u0){o.graphSet.push(E);for(u=0;ur.count?0:r.graph},Js=function e(t,n,r,i){var a=i.graphSet[r];if(-10)var s=(u=r.nodeOverlap*o)*i/(g=Math.sqrt(i*i+a*a)),l=u*a/g;else{var u,c=ll(e,i,a),d=ll(t,-1*i,-1*a),h=d.x-c.x,p=d.y-c.y,f=h*h+p*p,g=Math.sqrt(f);s=(u=(e.nodeRepulsion+t.nodeRepulsion)/f)*h/g,l=u*p/g}e.isLocked||(e.offsetX-=s,e.offsetY-=l),t.isLocked||(t.offsetX+=s,t.offsetY+=l)}},sl=function(e,t,n,r){if(n>0)var i=e.maxX-t.minX;else i=t.maxX-e.minX;if(r>0)var a=e.maxY-t.minY;else a=t.maxY-e.minY;return i>=0&&a>=0?Math.sqrt(i*i+a*a):0},ll=function(e,t,n){var r=e.positionX,i=e.positionY,a=e.height||1,o=e.width||1,s=n/t,l=a/o,u={};return 0===t&&0n?(u.x=r,u.y=i+a/2,u):0t&&-1*l<=s&&s<=l?(u.x=r-o/2,u.y=i-o*n/2/t,u):0=l)?(u.x=r+a*t/2/n,u.y=i+a/2,u):0>n&&(s<=-1*l||s>=l)?(u.x=r-a*t/2/n,u.y=i-a/2,u):u},ul=function(e,t){for(var n=0;n1){var f=t.gravity*d/p,g=t.gravity*h/p;c.offsetX+=f,c.offsetY+=g}}}}},dl=function(e,t){var n=[],r=0,i=-1;for(n.push.apply(n,e.graphSet[0]),i+=e.graphSet[0].length;r<=i;){var a=n[r++],o=e.idToIndex[a],s=e.layoutNodes[o],l=s.children;if(0n)var i={x:n*e/r,y:n*t/r};else i={x:e,y:t};return i},fl=function e(t,n){var r=t.parentId;if(null!=r){var i=n.layoutNodes[n.idToIndex[r]],a=!1;return(null==i.maxX||t.maxX+i.padRight>i.maxX)&&(i.maxX=t.maxX+i.padRight,a=!0),(null==i.minX||t.minX-i.padLefti.maxY)&&(i.maxY=t.maxY+i.padBottom,a=!0),(null==i.minY||t.minY-i.padTopf&&(d+=p+t.componentSpacing,c=0,h=0,p=0)}}},vl={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,avoidOverlapPadding:10,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,condense:!1,rows:void 0,cols:void 0,position:function(e){},sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:function(e,t){return!0},ready:void 0,stop:void 0,transform:function(e,t){return t}};function yl(e){this.options=L({},vl,e)}yl.prototype.run=function(){var e=this.options,t=e,n=e.cy,r=t.eles,i=r.nodes().not(":parent");t.sort&&(i=i.sort(t.sort));var a=_t(t.boundingBox?t.boundingBox:{x1:0,y1:0,w:n.width(),h:n.height()});if(0===a.h||0===a.w)r.nodes().layoutPositions(this,t,(function(e){return{x:a.x1,y:a.y1}}));else{var o=i.size(),s=Math.sqrt(o*a.h/a.w),l=Math.round(s),u=Math.round(a.w/a.h*s),c=function(e){if(null==e)return Math.min(l,u);Math.min(l,u)==l?l=e:u=e},d=function(e){if(null==e)return Math.max(l,u);Math.max(l,u)==l?l=e:u=e},h=t.rows,p=null!=t.cols?t.cols:t.columns;if(null!=h&&null!=p)l=h,u=p;else if(null!=h&&null==p)l=h,u=Math.ceil(o/l);else if(null==h&&null!=p)u=p,l=Math.ceil(o/u);else if(u*l>o){var f=c(),g=d();(f-1)*g>=o?c(f-1):(g-1)*f>=o&&d(g-1)}else for(;u*l=o?d(y+1):c(v+1)}var m=a.w/u,b=a.h/l;if(t.condense&&(m=0,b=0),t.avoidOverlap)for(var x=0;x=u&&(B=0,M++)},z={},I=0;I(r=qt(e,t,x[w],x[w+1],x[w+2],x[w+3])))return v(n,r),!0}else if("bezier"===a.edgeType||"multibezier"===a.edgeType||"self"===a.edgeType||"compound"===a.edgeType)for(x=a.allpts,w=0;w+5(r=jt(e,t,x[w],x[w+1],x[w+2],x[w+3],x[w+4],x[w+5])))return v(n,r),!0;m=m||i.source,b=b||i.target;var E=o.getArrowWidth(l,c),k=[{name:"source",x:a.arrowStartX,y:a.arrowStartY,angle:a.srcArrowAngle},{name:"target",x:a.arrowEndX,y:a.arrowEndY,angle:a.tgtArrowAngle},{name:"mid-source",x:a.midX,y:a.midY,angle:a.midsrcArrowAngle},{name:"mid-target",x:a.midX,y:a.midY,angle:a.midtgtArrowAngle}];for(w=0;w0&&(y(m),y(b))}function b(e,t,n){return Ue(e,t,n)}function x(n,r){var i,a=n._private,o=f;i=r?r+"-":"",n.boundingBox();var s=a.labelBounds[r||"main"],l=n.pstyle(i+"label").value;if("yes"===n.pstyle("text-events").strValue&&l){var u=b(a.rscratch,"labelX",r),c=b(a.rscratch,"labelY",r),d=b(a.rscratch,"labelAngle",r),h=n.pstyle(i+"text-margin-x").pfValue,p=n.pstyle(i+"text-margin-y").pfValue,g=s.x1-o-h,y=s.x2+o-h,m=s.y1-o-p,x=s.y2+o-p;if(d){var w=Math.cos(d),E=Math.sin(d),k=function(e,t){return{x:(e-=u)*w-(t-=c)*E+u,y:e*E+t*w+c}},C=k(g,m),S=k(g,x),P=k(y,m),D=k(y,x),T=[C.x+h,C.y+p,P.x+h,P.y+p,D.x+h,D.y+p,S.x+h,S.y+p];if(Yt(e,t,T))return v(n),!0}else if(Lt(s,e,t))return v(n),!0}}n&&(l=l.interactive);for(var w=l.length-1;w>=0;w--){var E=l[w];E.isNode()?y(E)||x(E):m(E)||x(E)||x(E,"source")||x(E,"target")}return u},getAllInBox:function(e,t,n,r){for(var i,a,o=this.getCachedZSortedEles().interactive,s=[],l=Math.min(e,n),u=Math.max(e,n),c=Math.min(t,r),d=Math.max(t,r),h=_t({x1:e=l,y1:t=c,x2:n=u,y2:r=d}),p=0;p0?-(Math.PI-a.ang):Math.PI+a.ang),Zl(t,n,Ul),zl=Gl.nx*Ul.ny-Gl.ny*Ul.nx,Il=Gl.nx*Ul.nx-Gl.ny*-Ul.ny,Ol=Math.asin(Math.max(-1,Math.min(1,zl))),Math.abs(Ol)<1e-6)return Bl=t.x,Nl=t.y,void(Vl=jl=0);Al=1,Ll=!1,Il<0?Ol<0?Ol=Math.PI+Ol:(Ol=Math.PI-Ol,Al=-1,Ll=!0):Ol>0&&(Al=-1,Ll=!0),jl=void 0!==t.radius?t.radius:r,Rl=Ol/2,ql=Math.min(Gl.len/2,Ul.len/2),i?(Fl=Math.abs(Math.cos(Rl)*jl/Math.sin(Rl)))>ql?(Fl=ql,Vl=Math.abs(Fl*Math.sin(Rl)/Math.cos(Rl))):Vl=jl:(Fl=Math.min(ql,jl),Vl=Math.abs(Fl*Math.sin(Rl)/Math.cos(Rl))),Wl=t.x+Ul.nx*Fl,Hl=t.y+Ul.ny*Fl,Bl=Wl-Ul.ny*Vl*Al,Nl=Hl+Ul.nx*Vl*Al,Yl=t.x+Gl.nx*Fl,Xl=t.y+Gl.ny*Fl,Kl=t};function Ql(e,t){0===t.radius?e.lineTo(t.cx,t.cy):e.arc(t.cx,t.cy,t.radius,t.startAngle,t.endAngle,t.counterClockwise)}function Jl(e,t,n,r){var i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];return 0===r||0===t.radius?{cx:t.x,cy:t.y,radius:0,startX:t.x,startY:t.y,stopX:t.x,stopY:t.y,startAngle:void 0,endAngle:void 0,counterClockwise:void 0}:($l(e,t,n,r,i),{cx:Bl,cy:Nl,radius:Vl,startX:Yl,startY:Xl,stopX:Wl,stopY:Hl,startAngle:Gl.ang+Math.PI/2*Al,endAngle:Ul.ang-Math.PI/2*Al,counterClockwise:Ll})}var eu={};function tu(e){var t=[];if(null!=e){for(var n=0;n0?Math.max(e-t,0):Math.min(e+t,0)},w=x(m,v),E=x(b,y),k=!1;"auto"===c?u=Math.abs(w)>Math.abs(E)?"horizontal":"vertical":"upward"===c||"downward"===c?(u="vertical",k=!0):"leftward"!==c&&"rightward"!==c||(u="horizontal",k=!0);var C,S="vertical"===u,P=S?E:w,D=S?b:m,T=Et(D),_=!1;(k&&(h||f)||!("downward"===c&&D<0||"upward"===c&&D>0||"leftward"===c&&D>0||"rightward"===c&&D<0)||(P=(T*=-1)*Math.abs(P),_=!0),h)?C=(p<0?1+p:p)*P:C=(p<0?P:0)+p*T;var M=function(e){return Math.abs(e)=Math.abs(P)},B=M(C),N=M(Math.abs(P)-Math.abs(C));if((B||N)&&!_)if(S){var z=Math.abs(D)<=a/2,I=Math.abs(m)<=o/2;if(z){var A=(r.x1+r.x2)/2,L=r.y1,O=r.y2;n.segpts=[A,L,A,O]}else if(I){var R=(r.y1+r.y2)/2,V=r.x1,F=r.x2;n.segpts=[V,R,F,R]}else n.segpts=[r.x1,r.y2]}else{var j=Math.abs(D)<=i/2,q=Math.abs(b)<=s/2;if(j){var Y=(r.y1+r.y2)/2,X=r.x1,W=r.x2;n.segpts=[X,Y,W,Y]}else if(q){var H=(r.x1+r.x2)/2,K=r.y1,G=r.y2;n.segpts=[H,K,H,G]}else n.segpts=[r.x2,r.y1]}else if(S){var U=r.y1+C+(l?a/2*T:0),Z=r.x1,$=r.x2;n.segpts=[Z,U,$,U]}else{var Q=r.x1+C+(l?i/2*T:0),J=r.y1,ee=r.y2;n.segpts=[Q,J,Q,ee]}if(n.isRound){var te=e.pstyle("taxi-radius").value,ne="arc-radius"===e.pstyle("radius-type").value[0];n.radii=new Array(n.segpts.length/2).fill(te),n.isArcRadius=new Array(n.segpts.length/2).fill(ne)}},eu.tryToCorrectInvalidPoints=function(e,t){var n=e._private.rscratch;if("bezier"===n.edgeType){var r=t.srcPos,i=t.tgtPos,a=t.srcW,o=t.srcH,s=t.tgtW,l=t.tgtH,u=t.srcShape,c=t.tgtShape,d=t.srcCornerRadius,h=t.tgtCornerRadius,p=t.srcRs,f=t.tgtRs,g=!x(n.startX)||!x(n.startY),v=!x(n.arrowStartX)||!x(n.arrowStartY),y=!x(n.endX)||!x(n.endY),m=!x(n.arrowEndX)||!x(n.arrowEndY),b=3*(this.getArrowWidth(e.pstyle("width").pfValue,e.pstyle("arrow-scale").value)*this.arrowShapeWidth),w=kt({x:n.ctrlpts[0],y:n.ctrlpts[1]},{x:n.startX,y:n.startY}),E=wh.poolIndex()){var p=d;d=h,h=p}var f=s.srcPos=d.position(),g=s.tgtPos=h.position(),v=s.srcW=d.outerWidth(),y=s.srcH=d.outerHeight(),m=s.tgtW=h.outerWidth(),b=s.tgtH=h.outerHeight(),w=s.srcShape=n.nodeShapes[t.getNodeShape(d)],E=s.tgtShape=n.nodeShapes[t.getNodeShape(h)],k=s.srcCornerRadius="auto"===d.pstyle("corner-radius").value?"auto":d.pstyle("corner-radius").pfValue,C=s.tgtCornerRadius="auto"===h.pstyle("corner-radius").value?"auto":h.pstyle("corner-radius").pfValue,S=s.tgtRs=h._private.rscratch,P=s.srcRs=d._private.rscratch;s.dirCounts={north:0,west:0,south:0,east:0,northwest:0,southwest:0,northeast:0,southeast:0};for(var D=0;D0){var H=u,K=Ct(H,bt(t)),G=Ct(H,bt(W)),U=K;if(G2)Ct(H,{x:W[2],y:W[3]})0){var le=c,ue=Ct(le,bt(t)),ce=Ct(le,bt(se)),de=ue;if(ce2)Ct(le,{x:se[2],y:se[3]})=c||b){d={cp:v,segment:m};break}}if(d)break}var x=d.cp,w=d.segment,E=(c-p)/w.length,k=w.t1-w.t0,C=u?w.t0+k*E:w.t1-k*E;C=Tt(0,C,1),t=Dt(x.p0,x.p1,x.p2,C),l=function(e,t,n,r){var i=Tt(0,r-.001,1),a=Tt(0,r+.001,1),o=Dt(e,t,n,i),s=Dt(e,t,n,a);return su(o,s)}(x.p0,x.p1,x.p2,C);break;case"straight":case"segments":case"haystack":for(var S,P,D,T,_=0,M=r.allpts.length,B=0;B+3=c));B+=2);var N=(c-P)/S;N=Tt(0,N,1),t=function(e,t,n,r){var i=t.x-e.x,a=t.y-e.y,o=kt(e,t),s=i/o,l=a/o;return n=null==n?0:n,r=null!=r?r:n*o,{x:e.x+s*r,y:e.y+l*r}}(D,T,N),l=su(D,T)}o("labelX",s,t.x),o("labelY",s,t.y),o("labelAutoAngle",s,l)}};l("source"),l("target"),this.applyLabelDimensions(e)}},au.applyLabelDimensions=function(e){this.applyPrefixedLabelDimensions(e),e.isEdge()&&(this.applyPrefixedLabelDimensions(e,"source"),this.applyPrefixedLabelDimensions(e,"target"))},au.applyPrefixedLabelDimensions=function(e,t){var n=e._private,r=this.getLabelText(e,t),i=this.calculateLabelDimensions(e,r),a=e.pstyle("line-height").pfValue,o=e.pstyle("text-wrap").strValue,s=Ue(n.rscratch,"labelWrapCachedLines",t)||[],l="wrap"!==o?1:Math.max(s.length,1),u=i.height/l,c=u*a,d=i.width,h=i.height+(l-1)*(a-1)*u;Ze(n.rstyle,"labelWidth",t,d),Ze(n.rscratch,"labelWidth",t,d),Ze(n.rstyle,"labelHeight",t,h),Ze(n.rscratch,"labelHeight",t,h),Ze(n.rscratch,"labelLineHeight",t,c)},au.getLabelText=function(e,t){var n=e._private,r=t?t+"-":"",i=e.pstyle(r+"label").strValue,a=e.pstyle("text-transform").value,o=function(e,r){return r?(Ze(n.rscratch,e,t,r),r):Ue(n.rscratch,e,t)};if(!i)return"";"none"==a||("uppercase"==a?i=i.toUpperCase():"lowercase"==a&&(i=i.toLowerCase()));var s=e.pstyle("text-wrap").value;if("wrap"===s){var u=o("labelKey");if(null!=u&&o("labelWrapKey")===u)return o("labelWrapCachedText");for(var c=i.split("\n"),d=e.pstyle("text-max-width").pfValue,h="anywhere"===e.pstyle("text-overflow-wrap").value,p=[],f=/[\s\u200b]+|$/g,g=0;gd){var b,x="",w=0,E=l(v.matchAll(f));try{for(E.s();!(b=E.n()).done;){var k=b.value,C=k[0],S=v.substring(w,k.index);w=k.index+C.length;var P=0===x.length?S:x+S+C;this.calculateLabelDimensions(e,P).width<=d?x+=S+C:(x&&p.push(x),x=S+C)}}catch(e){E.e(e)}finally{E.f()}x.match(/^[\s\u200b]+$/)||p.push(x)}else p.push(v)}o("labelWrapCachedLines",p),i=o("labelWrapCachedText",p.join("\n")),o("labelWrapKey",u)}else if("ellipsis"===s){var D=e.pstyle("text-max-width").pfValue,T="",_=!1;if(this.calculateLabelDimensions(e,i).widthD)break;T+=i[M],M===i.length-1&&(_=!0)}return _||(T+="…"),T}return i},au.getLabelJustification=function(e){var t=e.pstyle("text-justification").strValue,n=e.pstyle("text-halign").strValue;if("auto"!==t)return t;if(!e.isNode())return"center";switch(n){case"left":return"right";case"right":return"left";default:return"center"}},au.calculateLabelDimensions=function(e,t){var n=this,r=n.cy.window().document,i=Te(t,e._private.labelDimsKey),a=n.labelDimCache||(n.labelDimCache=[]),o=a[i];if(null!=o)return o;var s=e.pstyle("font-style").strValue,l=e.pstyle("font-size").pfValue,u=e.pstyle("font-family").strValue,c=e.pstyle("font-weight").strValue,d=this.labelCalcCanvas,h=this.labelCalcCanvasContext;if(!d){d=this.labelCalcCanvas=r.createElement("canvas"),h=this.labelCalcCanvasContext=d.getContext("2d");var p=d.style;p.position="absolute",p.left="-9999px",p.top="-9999px",p.zIndex="-1",p.visibility="hidden",p.pointerEvents="none"}h.font="".concat(s," ").concat(c," ").concat(l,"px ").concat(u);for(var f=0,g=0,v=t.split("\n"),y=0;y1&&void 0!==arguments[1])||arguments[1];if(t.merge(e),n)for(var r=0;r=e.desktopTapThreshold2}var D=i(t);v&&(e.hoverData.tapholdCancelled=!0);n=!0,r(g,["mousemove","vmousemove","tapdrag"],t,{x:c[0],y:c[1]});var T=function(){e.data.bgActivePosistion=void 0,e.hoverData.selecting||o.emit({originalEvent:t,type:"boxstart",position:{x:c[0],y:c[1]}}),f[4]=1,e.hoverData.selecting=!0,e.redrawHint("select",!0),e.redraw()};if(3===e.hoverData.which){if(v){var _={originalEvent:t,type:"cxtdrag",position:{x:c[0],y:c[1]}};m?m.emit(_):o.emit(_),e.hoverData.cxtDragged=!0,e.hoverData.cxtOver&&g===e.hoverData.cxtOver||(e.hoverData.cxtOver&&e.hoverData.cxtOver.emit({originalEvent:t,type:"cxtdragout",position:{x:c[0],y:c[1]}}),e.hoverData.cxtOver=g,g&&g.emit({originalEvent:t,type:"cxtdragover",position:{x:c[0],y:c[1]}}))}}else if(e.hoverData.dragging){if(n=!0,o.panningEnabled()&&o.userPanningEnabled()){var M;if(e.hoverData.justStartedPan){var B=e.hoverData.mdownPos;M={x:(c[0]-B[0])*s,y:(c[1]-B[1])*s},e.hoverData.justStartedPan=!1}else M={x:b[0]*s,y:b[1]*s};o.panBy(M),o.emit("dragpan"),e.hoverData.dragged=!0}c=e.projectIntoViewport(t.clientX,t.clientY)}else if(1!=f[4]||null!=m&&!m.pannable()){if(m&&m.pannable()&&m.active()&&m.unactivate(),m&&m.grabbed()||g==y||(y&&r(y,["mouseout","tapdragout"],t,{x:c[0],y:c[1]}),g&&r(g,["mouseover","tapdragover"],t,{x:c[0],y:c[1]}),e.hoverData.last=g),m)if(v){if(o.boxSelectionEnabled()&&D)m&&m.grabbed()&&(d(w),m.emit("freeon"),w.emit("free"),e.dragData.didDrag&&(m.emit("dragfreeon"),w.emit("dragfree"))),T();else if(m&&m.grabbed()&&e.nodeIsDraggable(m)){var N=!e.dragData.didDrag;N&&e.redrawHint("eles",!0),e.dragData.didDrag=!0,e.hoverData.draggingEles||u(w,{inDragLayer:!0});var z={x:0,y:0};if(x(b[0])&&x(b[1])&&(z.x+=b[0],z.y+=b[1],N)){var I=e.hoverData.dragDelta;I&&x(I[0])&&x(I[1])&&(z.x+=I[0],z.y+=I[1])}e.hoverData.draggingEles=!0,w.silentShift(z).emit("position drag"),e.redrawHint("drag",!0),e.redraw()}}else!function(){var t=e.hoverData.dragDelta=e.hoverData.dragDelta||[];0===t.length?(t.push(b[0]),t.push(b[1])):(t[0]+=b[0],t[1]+=b[1])}();n=!0}else if(v){if(e.hoverData.dragging||!o.boxSelectionEnabled()||!D&&o.panningEnabled()&&o.userPanningEnabled()){if(!e.hoverData.selecting&&o.panningEnabled()&&o.userPanningEnabled()){a(m,e.hoverData.downs)&&(e.hoverData.dragging=!0,e.hoverData.justStartedPan=!0,f[4]=0,e.data.bgActivePosistion=bt(h),e.redrawHint("select",!0),e.redraw())}}else T();m&&m.pannable()&&m.active()&&m.unactivate()}return f[2]=c[0],f[3]=c[1],n?(t.stopPropagation&&t.stopPropagation(),t.preventDefault&&t.preventDefault(),!1):void 0}}),!1),e.registerBinding(t,"mouseup",(function(t){if((1!==e.hoverData.which||1===t.which||!e.hoverData.capture)&&e.hoverData.capture){e.hoverData.capture=!1;var a=e.cy,o=e.projectIntoViewport(t.clientX,t.clientY),s=e.selection,l=e.findNearestElement(o[0],o[1],!0,!1),u=e.dragData.possibleDragElements,c=e.hoverData.down,h=i(t);if(e.data.bgActivePosistion&&(e.redrawHint("select",!0),e.redraw()),e.hoverData.tapholdCancelled=!0,e.data.bgActivePosistion=void 0,c&&c.unactivate(),3===e.hoverData.which){var p={originalEvent:t,type:"cxttapend",position:{x:o[0],y:o[1]}};if(c?c.emit(p):a.emit(p),!e.hoverData.cxtDragged){var f={originalEvent:t,type:"cxttap",position:{x:o[0],y:o[1]}};c?c.emit(f):a.emit(f)}e.hoverData.cxtDragged=!1,e.hoverData.which=null}else if(1===e.hoverData.which){if(r(l,["mouseup","tapend","vmouseup"],t,{x:o[0],y:o[1]}),e.dragData.didDrag||e.hoverData.dragged||e.hoverData.selecting||e.hoverData.isOverThresholdDrag||(r(c,["click","tap","vclick"],t,{x:o[0],y:o[1]}),b=!1,t.timeStamp-w<=a.multiClickDebounceTime()?(m&&clearTimeout(m),b=!0,w=null,r(c,["dblclick","dbltap","vdblclick"],t,{x:o[0],y:o[1]})):(m=setTimeout((function(){b||r(c,["oneclick","onetap","voneclick"],t,{x:o[0],y:o[1]})}),a.multiClickDebounceTime()),w=t.timeStamp)),null!=c||e.dragData.didDrag||e.hoverData.selecting||e.hoverData.dragged||i(t)||(a.$(n).unselect(["tapunselect"]),u.length>0&&e.redrawHint("eles",!0),e.dragData.possibleDragElements=u=a.collection()),l!=c||e.dragData.didDrag||e.hoverData.selecting||null!=l&&l._private.selectable&&(e.hoverData.dragging||("additive"===a.selectionType()||h?l.selected()?l.unselect(["tapunselect"]):l.select(["tapselect"]):h||(a.$(n).unmerge(l).unselect(["tapunselect"]),l.select(["tapselect"]))),e.redrawHint("eles",!0)),e.hoverData.selecting){var g=a.collection(e.getAllInBox(s[0],s[1],s[2],s[3]));e.redrawHint("select",!0),g.length>0&&e.redrawHint("eles",!0),a.emit({type:"boxend",originalEvent:t,position:{x:o[0],y:o[1]}});var v=function(e){return e.selectable()&&!e.selected()};"additive"===a.selectionType()||h||a.$(n).unmerge(g).unselect(),g.emit("box").stdFilter(v).select().emit("boxselect"),e.redraw()}if(e.hoverData.dragging&&(e.hoverData.dragging=!1,e.redrawHint("select",!0),e.redrawHint("eles",!0),e.redraw()),!s[4]){e.redrawHint("drag",!0),e.redrawHint("eles",!0);var y=c&&c.grabbed();d(u),y&&(c.emit("freeon"),u.emit("free"),e.dragData.didDrag&&(c.emit("dragfreeon"),u.emit("dragfree")))}}s[4]=0,e.hoverData.down=null,e.hoverData.cxtStarted=!1,e.hoverData.draggingEles=!1,e.hoverData.selecting=!1,e.hoverData.isOverThresholdDrag=!1,e.dragData.didDrag=!1,e.hoverData.dragged=!1,e.hoverData.dragDelta=[],e.hoverData.mdownPos=null,e.hoverData.mdownGPos=null,e.hoverData.which=null}}),!1);var k,C,S,P,D,T,_,M,B,N,z,I,A,L=function(t){if(!e.scrollingPage){var n=e.cy,r=n.zoom(),i=n.pan(),a=e.projectIntoViewport(t.clientX,t.clientY),o=[a[0]*r+i.x,a[1]*r+i.y];if(e.hoverData.draggingEles||e.hoverData.dragging||e.hoverData.cxtStarted||0!==e.selection[4])t.preventDefault();else if(n.panningEnabled()&&n.userPanningEnabled()&&n.zoomingEnabled()&&n.userZoomingEnabled()){var s;t.preventDefault(),e.data.wheelZooming=!0,clearTimeout(e.data.wheelTimeout),e.data.wheelTimeout=setTimeout((function(){e.data.wheelZooming=!1,e.redrawHint("eles",!0),e.redraw()}),150),s=null!=t.deltaY?t.deltaY/-250:null!=t.wheelDeltaY?t.wheelDeltaY/1e3:t.wheelDelta/1e3,s*=e.wheelSensitivity,1===t.deltaMode&&(s*=33);var l=n.zoom()*Math.pow(10,s);"gesturechange"===t.type&&(l=e.gestureStartZoom*t.scale),n.zoom({level:l,renderedPosition:{x:o[0],y:o[1]}}),n.emit("gesturechange"===t.type?"pinchzoom":"scrollzoom")}}};e.registerBinding(e.container,"wheel",L,!0),e.registerBinding(t,"scroll",(function(t){e.scrollingPage=!0,clearTimeout(e.scrollingPageTimeout),e.scrollingPageTimeout=setTimeout((function(){e.scrollingPage=!1}),250)}),!0),e.registerBinding(e.container,"gesturestart",(function(t){e.gestureStartZoom=e.cy.zoom(),e.hasTouchStarted||t.preventDefault()}),!0),e.registerBinding(e.container,"gesturechange",(function(t){e.hasTouchStarted||L(t)}),!0),e.registerBinding(e.container,"mouseout",(function(t){var n=e.projectIntoViewport(t.clientX,t.clientY);e.cy.emit({originalEvent:t,type:"mouseout",position:{x:n[0],y:n[1]}})}),!1),e.registerBinding(e.container,"mouseover",(function(t){var n=e.projectIntoViewport(t.clientX,t.clientY);e.cy.emit({originalEvent:t,type:"mouseover",position:{x:n[0],y:n[1]}})}),!1);var O,R,V,F,j,q,Y,X=function(e,t,n,r){return Math.sqrt((n-e)*(n-e)+(r-t)*(r-t))},W=function(e,t,n,r){return(n-e)*(n-e)+(r-t)*(r-t)};if(e.registerBinding(e.container,"touchstart",O=function(t){if(e.hasTouchStarted=!0,E(t)){p(),e.touchData.capture=!0,e.data.bgActivePosistion=void 0;var n=e.cy,i=e.touchData.now,a=e.touchData.earlier;if(t.touches[0]){var o=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);i[0]=o[0],i[1]=o[1]}if(t.touches[1]){o=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);i[2]=o[0],i[3]=o[1]}if(t.touches[2]){o=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);i[4]=o[0],i[5]=o[1]}if(t.touches[1]){e.touchData.singleTouchMoved=!0,d(e.dragData.touchDragEles);var l=e.findContainerClientCoords();B=l[0],N=l[1],z=l[2],I=l[3],k=t.touches[0].clientX-B,C=t.touches[0].clientY-N,S=t.touches[1].clientX-B,P=t.touches[1].clientY-N,A=0<=k&&k<=z&&0<=S&&S<=z&&0<=C&&C<=I&&0<=P&&P<=I;var h=n.pan(),f=n.zoom();D=X(k,C,S,P),T=W(k,C,S,P),M=[((_=[(k+S)/2,(C+P)/2])[0]-h.x)/f,(_[1]-h.y)/f];if(T<4e4&&!t.touches[2]){var g=e.findNearestElement(i[0],i[1],!0,!0),v=e.findNearestElement(i[2],i[3],!0,!0);return g&&g.isNode()?(g.activate().emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start=g):v&&v.isNode()?(v.activate().emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start=v):n.emit({originalEvent:t,type:"cxttapstart",position:{x:i[0],y:i[1]}}),e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxt=!0,e.touchData.cxtDragged=!1,e.data.bgActivePosistion=void 0,void e.redraw()}}if(t.touches[2])n.boxSelectionEnabled()&&t.preventDefault();else if(t.touches[1]);else if(t.touches[0]){var y=e.findNearestElements(i[0],i[1],!0,!0),m=y[0];if(null!=m&&(m.activate(),e.touchData.start=m,e.touchData.starts=y,e.nodeIsGrabbable(m))){var b=e.dragData.touchDragEles=n.collection(),x=null;e.redrawHint("eles",!0),e.redrawHint("drag",!0),m.selected()?(x=n.$((function(t){return t.selected()&&e.nodeIsGrabbable(t)})),u(x,{addToList:b})):c(m,{addToList:b}),s(m);var w=function(e){return{originalEvent:t,type:e,position:{x:i[0],y:i[1]}}};m.emit(w("grabon")),x?x.forEach((function(e){e.emit(w("grab"))})):m.emit(w("grab"))}r(m,["touchstart","tapstart","vmousedown"],t,{x:i[0],y:i[1]}),null==m&&(e.data.bgActivePosistion={x:o[0],y:o[1]},e.redrawHint("select",!0),e.redraw()),e.touchData.singleTouchMoved=!1,e.touchData.singleTouchStartTime=+new Date,clearTimeout(e.touchData.tapholdTimeout),e.touchData.tapholdTimeout=setTimeout((function(){!1!==e.touchData.singleTouchMoved||e.pinching||e.touchData.selecting||r(e.touchData.start,["taphold"],t,{x:i[0],y:i[1]})}),e.tapholdDuration)}if(t.touches.length>=1){for(var L=e.touchData.startPosition=[null,null,null,null,null,null],O=0;O=e.touchTapThreshold2}if(n&&e.touchData.cxt){t.preventDefault();var w=t.touches[0].clientX-B,_=t.touches[0].clientY-N,z=t.touches[1].clientX-B,I=t.touches[1].clientY-N,L=W(w,_,z,I);if(L/T>=2.25||L>=22500){e.touchData.cxt=!1,e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);var O={originalEvent:t,type:"cxttapend",position:{x:s[0],y:s[1]}};e.touchData.start?(e.touchData.start.unactivate().emit(O),e.touchData.start=null):o.emit(O)}}if(n&&e.touchData.cxt){O={originalEvent:t,type:"cxtdrag",position:{x:s[0],y:s[1]}};e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),e.touchData.start?e.touchData.start.emit(O):o.emit(O),e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxtDragged=!0;var R=e.findNearestElement(s[0],s[1],!0,!0);e.touchData.cxtOver&&R===e.touchData.cxtOver||(e.touchData.cxtOver&&e.touchData.cxtOver.emit({originalEvent:t,type:"cxtdragout",position:{x:s[0],y:s[1]}}),e.touchData.cxtOver=R,R&&R.emit({originalEvent:t,type:"cxtdragover",position:{x:s[0],y:s[1]}}))}else if(n&&t.touches[2]&&o.boxSelectionEnabled())t.preventDefault(),e.data.bgActivePosistion=void 0,this.lastThreeTouch=+new Date,e.touchData.selecting||o.emit({originalEvent:t,type:"boxstart",position:{x:s[0],y:s[1]}}),e.touchData.selecting=!0,e.touchData.didSelect=!0,i[4]=1,i&&0!==i.length&&void 0!==i[0]?(i[2]=(s[0]+s[2]+s[4])/3,i[3]=(s[1]+s[3]+s[5])/3):(i[0]=(s[0]+s[2]+s[4])/3,i[1]=(s[1]+s[3]+s[5])/3,i[2]=(s[0]+s[2]+s[4])/3+1,i[3]=(s[1]+s[3]+s[5])/3+1),e.redrawHint("select",!0),e.redraw();else if(n&&t.touches[1]&&!e.touchData.didSelect&&o.zoomingEnabled()&&o.panningEnabled()&&o.userZoomingEnabled()&&o.userPanningEnabled()){if(t.preventDefault(),e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),ee=e.dragData.touchDragEles){e.redrawHint("drag",!0);for(var V=0;V0&&!e.hoverData.draggingEles&&!e.swipePanning&&null!=e.data.bgActivePosistion&&(e.data.bgActivePosistion=void 0,e.redrawHint("select",!0),e.redraw())}},!1),e.registerBinding(t,"touchcancel",V=function(t){var n=e.touchData.start;e.touchData.capture=!1,n&&n.unactivate()}),e.registerBinding(t,"touchend",F=function(t){var i=e.touchData.start;if(e.touchData.capture){0===t.touches.length&&(e.touchData.capture=!1),t.preventDefault();var a=e.selection;e.swipePanning=!1,e.hoverData.draggingEles=!1;var o,s=e.cy,l=s.zoom(),u=e.touchData.now,c=e.touchData.earlier;if(t.touches[0]){var h=e.projectIntoViewport(t.touches[0].clientX,t.touches[0].clientY);u[0]=h[0],u[1]=h[1]}if(t.touches[1]){h=e.projectIntoViewport(t.touches[1].clientX,t.touches[1].clientY);u[2]=h[0],u[3]=h[1]}if(t.touches[2]){h=e.projectIntoViewport(t.touches[2].clientX,t.touches[2].clientY);u[4]=h[0],u[5]=h[1]}if(i&&i.unactivate(),e.touchData.cxt){if(o={originalEvent:t,type:"cxttapend",position:{x:u[0],y:u[1]}},i?i.emit(o):s.emit(o),!e.touchData.cxtDragged){var p={originalEvent:t,type:"cxttap",position:{x:u[0],y:u[1]}};i?i.emit(p):s.emit(p)}return e.touchData.start&&(e.touchData.start._private.grabbed=!1),e.touchData.cxt=!1,e.touchData.start=null,void e.redraw()}if(!t.touches[2]&&s.boxSelectionEnabled()&&e.touchData.selecting){e.touchData.selecting=!1;var f=s.collection(e.getAllInBox(a[0],a[1],a[2],a[3]));a[0]=void 0,a[1]=void 0,a[2]=void 0,a[3]=void 0,a[4]=0,e.redrawHint("select",!0),s.emit({type:"boxend",originalEvent:t,position:{x:u[0],y:u[1]}});f.emit("box").stdFilter((function(e){return e.selectable()&&!e.selected()})).select().emit("boxselect"),f.nonempty()&&e.redrawHint("eles",!0),e.redraw()}if(null!=i&&i.unactivate(),t.touches[2])e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);else if(t.touches[1]);else if(t.touches[0]);else if(!t.touches[0]){e.data.bgActivePosistion=void 0,e.redrawHint("select",!0);var g=e.dragData.touchDragEles;if(null!=i){var v=i._private.grabbed;d(g),e.redrawHint("drag",!0),e.redrawHint("eles",!0),v&&(i.emit("freeon"),g.emit("free"),e.dragData.didDrag&&(i.emit("dragfreeon"),g.emit("dragfree"))),r(i,["touchend","tapend","vmouseup","tapdragout"],t,{x:u[0],y:u[1]}),i.unactivate(),e.touchData.start=null}else{var y=e.findNearestElement(u[0],u[1],!0,!0);r(y,["touchend","tapend","vmouseup","tapdragout"],t,{x:u[0],y:u[1]})}var m=e.touchData.startPosition[0]-u[0],b=m*m,x=e.touchData.startPosition[1]-u[1],w=(b+x*x)*l*l;e.touchData.singleTouchMoved||(i||s.$(":selected").unselect(["tapunselect"]),r(i,["tap","vclick"],t,{x:u[0],y:u[1]}),j=!1,t.timeStamp-Y<=s.multiClickDebounceTime()?(q&&clearTimeout(q),j=!0,Y=null,r(i,["dbltap","vdblclick"],t,{x:u[0],y:u[1]})):(q=setTimeout((function(){j||r(i,["onetap","voneclick"],t,{x:u[0],y:u[1]})}),s.multiClickDebounceTime()),Y=t.timeStamp)),null!=i&&!e.dragData.didDrag&&i._private.selectable&&w2){for(var p=[c[0],c[1]],f=Math.pow(p[0]-e,2)+Math.pow(p[1]-t,2),g=1;g0)return g[0]}return null},p=Object.keys(d),f=0;f0?u:Rt(i,a,e,t,n,r,o,s)},checkPoint:function(e,t,n,r,i,a,o,s){var l=2*(s="auto"===s?nn(r,i):s);if(Xt(e,t,this.points,a,o,r,i-l,[0,-1],n))return!0;if(Xt(e,t,this.points,a,o,r-l,i,[0,-1],n))return!0;var u=r/2+2*n,c=i/2+2*n;return!!Yt(e,t,[a-u,o-c,a-u,o,a+u,o,a+u,o-c])||(!!Kt(e,t,l,l,a+r/2-s,o+i/2-s,n)||!!Kt(e,t,l,l,a-r/2+s,o+i/2-s,n))}}},gu.registerNodeShapes=function(){var e=this.nodeShapes={},t=this;this.generateEllipse(),this.generatePolygon("triangle",Jt(3,0)),this.generateRoundPolygon("round-triangle",Jt(3,0)),this.generatePolygon("rectangle",Jt(4,0)),e.square=e.rectangle,this.generateRoundRectangle(),this.generateCutRectangle(),this.generateBarrel(),this.generateBottomRoundrectangle();var n=[0,1,1,0,0,-1,-1,0];this.generatePolygon("diamond",n),this.generateRoundPolygon("round-diamond",n),this.generatePolygon("pentagon",Jt(5,0)),this.generateRoundPolygon("round-pentagon",Jt(5,0)),this.generatePolygon("hexagon",Jt(6,0)),this.generateRoundPolygon("round-hexagon",Jt(6,0)),this.generatePolygon("heptagon",Jt(7,0)),this.generateRoundPolygon("round-heptagon",Jt(7,0)),this.generatePolygon("octagon",Jt(8,0)),this.generateRoundPolygon("round-octagon",Jt(8,0));var r=new Array(20),i=tn(5,0),a=tn(5,Math.PI/5),o=.5*(3-Math.sqrt(5));o*=1.57;for(var s=0;s=e.deqFastCost*g)break}else if(i){if(p>=e.deqCost*l||p>=e.deqAvgCost*s)break}else if(f>=e.deqNoDrawCost*(1e3/60))break;var v=e.deq(t,d,c);if(!(v.length>0))break;for(var y=0;y0&&(e.onDeqd(t,u),!i&&e.shouldRedraw(t,u,d,c)&&r())}),i(t))}}},wu=function(){function e(n){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Le;t(this,e),this.idsByKey=new $e,this.keyForId=new $e,this.cachesByLvl=new $e,this.lvls=[],this.getKey=n,this.doesEleInvalidateKey=r}return r(e,[{key:"getIdsFor",value:function(e){null==e&&Ve("Can not get id list for null key");var t=this.idsByKey,n=this.idsByKey.get(e);return n||(n=new Je,t.set(e,n)),n}},{key:"addIdForKey",value:function(e,t){null!=e&&this.getIdsFor(e).add(t)}},{key:"deleteIdForKey",value:function(e,t){null!=e&&this.getIdsFor(e).delete(t)}},{key:"getNumberOfIdsForKey",value:function(e){return null==e?0:this.getIdsFor(e).size}},{key:"updateKeyMappingFor",value:function(e){var t=e.id(),n=this.keyForId.get(t),r=this.getKey(e);this.deleteIdForKey(n,t),this.addIdForKey(r,t),this.keyForId.set(t,r)}},{key:"deleteKeyMappingFor",value:function(e){var t=e.id(),n=this.keyForId.get(t);this.deleteIdForKey(n,t),this.keyForId.delete(t)}},{key:"keyHasChangedFor",value:function(e){var t=e.id();return this.keyForId.get(t)!==this.getKey(e)}},{key:"isInvalid",value:function(e){return this.keyHasChangedFor(e)||this.doesEleInvalidateKey(e)}},{key:"getCachesAt",value:function(e){var t=this.cachesByLvl,n=this.lvls,r=t.get(e);return r||(r=new $e,t.set(e,r),n.push(e)),r}},{key:"getCache",value:function(e,t){return this.getCachesAt(t).get(e)}},{key:"get",value:function(e,t){var n=this.getKey(e),r=this.getCache(n,t);return null!=r&&this.updateKeyMappingFor(e),r}},{key:"getForCachedKey",value:function(e,t){var n=this.keyForId.get(e.id());return this.getCache(n,t)}},{key:"hasCache",value:function(e,t){return this.getCachesAt(t).has(e)}},{key:"has",value:function(e,t){var n=this.getKey(e);return this.hasCache(n,t)}},{key:"setCache",value:function(e,t,n){n.key=e,this.getCachesAt(t).set(e,n)}},{key:"set",value:function(e,t,n){var r=this.getKey(e);this.setCache(r,t,n),this.updateKeyMappingFor(e)}},{key:"deleteCache",value:function(e,t){this.getCachesAt(t).delete(e)}},{key:"delete",value:function(e,t){var n=this.getKey(e);this.deleteCache(n,t)}},{key:"invalidateKey",value:function(e){var t=this;this.lvls.forEach((function(n){return t.deleteCache(e,n)}))}},{key:"invalidate",value:function(e){var t=e.id(),n=this.keyForId.get(t);this.deleteKeyMappingFor(e);var r=this.doesEleInvalidateKey(e);return r&&this.invalidateKey(n),r||0===this.getNumberOfIdsForKey(n)}}]),e}(),Eu={dequeue:"dequeue",downscale:"downscale",highQuality:"highQuality"},ku=He({getKey:null,doesEleInvalidateKey:Le,drawElement:null,getBoundingBox:null,getRotationPoint:null,getRotationOffset:null,isVisible:Ae,allowEdgeTxrCaching:!0,allowParentTxrCaching:!0}),Cu=function(e,t){this.renderer=e,this.onDequeues=[];var n=ku(t);L(this,n),this.lookup=new wu(n.getKey,n.doesEleInvalidateKey),this.setupDequeueing()},Su=Cu.prototype;Su.reasons=Eu,Su.getTextureQueue=function(e){return this.eleImgCaches=this.eleImgCaches||{},this.eleImgCaches[e]=this.eleImgCaches[e]||[]},Su.getRetiredTextureQueue=function(e){var t=this.eleImgCaches.retired=this.eleImgCaches.retired||{};return t[e]=t[e]||[]},Su.getElementQueue=function(){return this.eleCacheQueue=this.eleCacheQueue||new rt((function(e,t){return t.reqs-e.reqs}))},Su.getElementKeyToQueue=function(){return this.eleKeyToCacheQueue=this.eleKeyToCacheQueue||{}},Su.getElement=function(e,t,n,r,i){var a=this,o=this.renderer,s=o.cy.zoom(),l=this.lookup;if(!t||0===t.w||0===t.h||isNaN(t.w)||isNaN(t.h)||!e.visible()||e.removed())return null;if(!a.allowEdgeTxrCaching&&e.isEdge()||!a.allowParentTxrCaching&&e.isParent())return null;if(null==r&&(r=Math.ceil(wt(s*n))),r<-4)r=-4;else if(s>=7.99||r>3)return null;var u=Math.pow(2,r),c=t.h*u,d=t.w*u,h=o.eleTextBiggerThanMin(e,u);if(!this.isVisible(e,h))return null;var p,f=l.get(e,r);if(f&&f.invalidated&&(f.invalidated=!1,f.texture.invalidatedWidth-=f.width),f)return f;if(p=c<=25?25:c<=50?50:50*Math.ceil(c/50),c>1024||d>1024)return null;var g=a.getTextureQueue(p),v=g[g.length-2],y=function(){return a.recycleTexture(p,d)||a.addTexture(p,d)};v||(v=g[g.length-1]),v||(v=y()),v.width-v.usedWidthr;D--)S=a.getElement(e,t,n,D,Eu.downscale);P()}else{var T;if(!x&&!w&&!E)for(var _=r-1;_>=-4;_--){var M=l.get(e,_);if(M){T=M;break}}if(b(T))return a.queueElement(e,r),T;v.context.translate(v.usedWidth,0),v.context.scale(u,u),this.drawElement(v.context,e,t,h,!1),v.context.scale(1/u,1/u),v.context.translate(-v.usedWidth,0)}return f={x:v.usedWidth,texture:v,level:r,scale:u,width:d,height:c,scaledLabelShown:h},v.usedWidth+=Math.ceil(d+8),v.eleCaches.push(f),l.set(e,r,f),a.checkTextureFullness(v),f},Su.invalidateElements=function(e){for(var t=0;t=.2*e.width&&this.retireTexture(e)},Su.checkTextureFullness=function(e){var t=this.getTextureQueue(e.height);e.usedWidth/e.width>.8&&e.fullnessChecks>=10?Ke(t,e):e.fullnessChecks++},Su.retireTexture=function(e){var t=e.height,n=this.getTextureQueue(t),r=this.lookup;Ke(n,e),e.retired=!0;for(var i=e.eleCaches,a=0;a=t)return a.retired=!1,a.usedWidth=0,a.invalidatedWidth=0,a.fullnessChecks=0,Ge(a.eleCaches),a.context.setTransform(1,0,0,1,0,0),a.context.clearRect(0,0,a.width,a.height),Ke(r,a),n.push(a),a}},Su.queueElement=function(e,t){var n=this.getElementQueue(),r=this.getElementKeyToQueue(),i=this.getKey(e),a=r[i];if(a)a.level=Math.max(a.level,t),a.eles.merge(e),a.reqs++,n.updateItem(a);else{var o={eles:e.spawn().merge(e),level:t,reqs:1,key:i};n.push(o),r[i]=o}},Su.dequeue=function(e){for(var t=this.getElementQueue(),n=this.getElementKeyToQueue(),r=[],i=this.lookup,a=0;a<1&&t.size()>0;a++){var o=t.pop(),s=o.key,l=o.eles[0],u=i.hasCache(l,o.level);if(n[s]=null,!u){r.push(o);var c=this.getBoundingBox(l);this.getElement(l,c,e,o.level,Eu.dequeue)}}return r},Su.removeFromQueue=function(e){var t=this.getElementQueue(),n=this.getElementKeyToQueue(),r=this.getKey(e),i=n[r];null!=i&&(1===i.eles.length?(i.reqs=Ie,t.updateItem(i),t.pop(),n[r]=null):i.eles.unmerge(e))},Su.onDequeue=function(e){this.onDequeues.push(e)},Su.offDequeue=function(e){Ke(this.onDequeues,e)},Su.setupDequeueing=xu({deqRedrawThreshold:100,deqCost:.15,deqAvgCost:.1,deqNoDrawCost:.9,deqFastCost:.9,deq:function(e,t,n){return e.dequeue(t,n)},onDeqd:function(e,t){for(var n=0;n=3.99||n>2)return null;r.validateLayersElesOrdering(n,e);var o,s,l=r.layersByLevel,u=Math.pow(2,n),c=l[n]=l[n]||[];if(r.levelIsComplete(n,e))return c;!function(){var t=function(t){if(r.validateLayersElesOrdering(t,e),r.levelIsComplete(t,e))return s=l[t],!0},i=function(e){if(!s)for(var r=n+e;-4<=r&&r<=2&&!t(r);r+=e);};i(1),i(-1);for(var a=c.length-1;a>=0;a--){var o=c[a];o.invalid&&Ke(c,o)}}();var d=function(t){var i=(t=t||{}).after;if(function(){if(!o){o=_t();for(var t=0;t16e6)return null;var a=r.makeLayer(o,n);if(null!=i){var s=c.indexOf(i)+1;c.splice(s,0,a)}else(void 0===t.insert||t.insert)&&c.unshift(a);return a};if(r.skipping&&!a)return null;for(var h=null,p=e.length/1,f=!a,g=0;g=p||!Ot(h.bb,v.boundingBox()))&&!(h=d({insert:!0,after:h})))return null;s||f?r.queueLayer(h,v):r.drawEleInLayer(h,v,n,t),h.eles.push(v),m[n]=h}}return s||(f?null:c)},Du.getEleLevelForLayerLevel=function(e,t){return e},Du.drawEleInLayer=function(e,t,n,r){var i=this.renderer,a=e.context,o=t.boundingBox();0!==o.w&&0!==o.h&&t.visible()&&(n=this.getEleLevelForLayerLevel(n,r),i.setImgSmoothing(a,!1),i.drawCachedElement(a,t,null,null,n,!0),i.setImgSmoothing(a,!0))},Du.levelIsComplete=function(e,t){var n=this.layersByLevel[e];if(!n||0===n.length)return!1;for(var r=0,i=0;i0)return!1;if(a.invalid)return!1;r+=a.eles.length}return r===t.length},Du.validateLayersElesOrdering=function(e,t){var n=this.layersByLevel[e];if(n)for(var r=0;r0){e=!0;break}}return e},Du.invalidateElements=function(e){var t=this;0!==e.length&&(t.lastInvalidationTime=we(),0!==e.length&&t.haveLayers()&&t.updateElementsInLayers(e,(function(e,n,r){t.invalidateLayer(e)})))},Du.invalidateLayer=function(e){if(this.lastInvalidationTime=we(),!e.invalid){var t=e.level,n=e.eles,r=this.layersByLevel[t];Ke(r,e),e.elesQueue=[],e.invalid=!0,e.replacement&&(e.replacement.invalid=!0);for(var i=0;i3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],o=this,s=t._private.rscratch;if((!a||t.visible())&&!s.badLine&&null!=s.allpts&&!isNaN(s.allpts[0])){var l;n&&(l=n,e.translate(-l.x1,-l.y1));var u=a?t.pstyle("opacity").value:1,c=a?t.pstyle("line-opacity").value:1,d=t.pstyle("curve-style").value,h=t.pstyle("line-style").value,p=t.pstyle("width").pfValue,f=t.pstyle("line-cap").value,g=t.pstyle("line-outline-width").value,v=t.pstyle("line-outline-color").value,y=u*c,m=u*c,b=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:y;"straight-triangle"===d?(o.eleStrokeStyle(e,t,n),o.drawEdgeTrianglePath(t,e,s.allpts)):(e.lineWidth=p,e.lineCap=f,o.eleStrokeStyle(e,t,n),o.drawEdgePath(t,e,s.allpts,h),e.lineCap="butt")},x=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:y;e.lineWidth=p+g,e.lineCap=f,g>0?(o.colorStrokeStyle(e,v[0],v[1],v[2],n),"straight-triangle"===d?o.drawEdgeTrianglePath(t,e,s.allpts):(o.drawEdgePath(t,e,s.allpts,h),e.lineCap="butt")):e.lineCap="butt"},w=function(){i&&o.drawEdgeOverlay(e,t)},E=function(){i&&o.drawEdgeUnderlay(e,t)},k=function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m;o.drawArrowheads(e,t,n)},C=function(){o.drawElementText(e,t,null,r)};e.lineJoin="round";var S="yes"===t.pstyle("ghost").value;if(S){var P=t.pstyle("ghost-offset-x").pfValue,D=t.pstyle("ghost-offset-y").pfValue,T=t.pstyle("ghost-opacity").value,_=y*T;e.translate(P,D),b(_),k(_),e.translate(-P,-D)}else x();E(),b(),k(),w(),C(),n&&e.translate(l.x1,l.y1)}}},Wu=function(e){if(!["overlay","underlay"].includes(e))throw new Error("Invalid state");return function(t,n){if(n.visible()){var r=n.pstyle("".concat(e,"-opacity")).value;if(0!==r){var i=this,a=i.usePaths(),o=n._private.rscratch,s=2*n.pstyle("".concat(e,"-padding")).pfValue,l=n.pstyle("".concat(e,"-color")).value;t.lineWidth=s,"self"!==o.edgeType||a?t.lineCap="round":t.lineCap="butt",i.colorStrokeStyle(t,l[0],l[1],l[2],r),i.drawEdgePath(n,t,o.allpts,"solid")}}}};Xu.drawEdgeOverlay=Wu("overlay"),Xu.drawEdgeUnderlay=Wu("underlay"),Xu.drawEdgePath=function(e,t,n,r){var i,a=e._private.rscratch,o=t,s=!1,u=this.usePaths(),c=e.pstyle("line-dash-pattern").pfValue,d=e.pstyle("line-dash-offset").pfValue;if(u){var h=n.join("$");a.pathCacheKey&&a.pathCacheKey===h?(i=t=a.pathCache,s=!0):(i=t=new Path2D,a.pathCacheKey=h,a.pathCache=i)}if(o.setLineDash)switch(r){case"dotted":o.setLineDash([1,1]);break;case"dashed":o.setLineDash(c),o.lineDashOffset=d;break;case"solid":o.setLineDash([])}if(!s&&!a.badLine)switch(t.beginPath&&t.beginPath(),t.moveTo(n[0],n[1]),a.edgeType){case"bezier":case"self":case"compound":case"multibezier":for(var p=2;p+35&&void 0!==arguments[5]?arguments[5]:5,o=arguments.length>6?arguments[6]:void 0;e.beginPath(),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.quadraticCurveTo(t+r,n,t+r,n+a),e.lineTo(t+r,n+i-a),e.quadraticCurveTo(t+r,n+i,t+r-a,n+i),e.lineTo(t+a,n+i),e.quadraticCurveTo(t,n+i,t,n+i-a),e.lineTo(t,n+a),e.quadraticCurveTo(t,n,t+a,n),e.closePath(),o?e.stroke():e.fill()}Ku.eleTextBiggerThanMin=function(e,t){if(!t){var n=e.cy().zoom(),r=this.getPixelRatio(),i=Math.ceil(wt(n*r));t=Math.pow(2,i)}return!(e.pstyle("font-size").pfValue*t5&&void 0!==arguments[5])||arguments[5],o=this;if(null==r){if(a&&!o.eleTextBiggerThanMin(t))return}else if(!1===r)return;if(t.isNode()){var s=t.pstyle("label");if(!s||!s.value)return;var l=o.getLabelJustification(t);e.textAlign=l,e.textBaseline="bottom"}else{var u=t.element()._private.rscratch.badLine,c=t.pstyle("label"),d=t.pstyle("source-label"),h=t.pstyle("target-label");if(u||(!c||!c.value)&&(!d||!d.value)&&(!h||!h.value))return;e.textAlign="center",e.textBaseline="bottom"}var p,f=!n;n&&(p=n,e.translate(-p.x1,-p.y1)),null==i?(o.drawText(e,t,null,f,a),t.isEdge()&&(o.drawText(e,t,"source",f,a),o.drawText(e,t,"target",f,a))):o.drawText(e,t,i,f,a),n&&e.translate(p.x1,p.y1)},Ku.getFontCache=function(e){var t;this.fontCaches=this.fontCaches||[];for(var n=0;n2&&void 0!==arguments[2])||arguments[2],r=t.pstyle("font-style").strValue,i=t.pstyle("font-size").pfValue+"px",a=t.pstyle("font-family").strValue,o=t.pstyle("font-weight").strValue,s=n?t.effectiveOpacity()*t.pstyle("text-opacity").value:1,l=t.pstyle("text-outline-opacity").value*s,u=t.pstyle("color").value,c=t.pstyle("text-outline-color").value;e.font=r+" "+o+" "+i+" "+a,e.lineJoin="round",this.colorFillStyle(e,u[0],u[1],u[2],s),this.colorStrokeStyle(e,c[0],c[1],c[2],l)},Ku.getTextAngle=function(e,t){var n=e._private.rscratch,r=t?t+"-":"",i=e.pstyle(r+"text-rotation"),a=Ue(n,"labelAngle",t);return"autorotate"===i.strValue?e.isEdge()?a:0:"none"===i.strValue?0:i.pfValue},Ku.drawText=function(e,t,n){var r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],i=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],a=t._private,o=a.rscratch,s=i?t.effectiveOpacity():1;if(!i||0!==s&&0!==t.pstyle("text-opacity").value){"main"===n&&(n=null);var l,u,c=Ue(o,"labelX",n),d=Ue(o,"labelY",n),h=this.getLabelText(t,n);if(null!=h&&""!==h&&!isNaN(c)&&!isNaN(d)){this.setupTextStyle(e,t,i);var p,f=n?n+"-":"",g=Ue(o,"labelWidth",n),v=Ue(o,"labelHeight",n),y=t.pstyle(f+"text-margin-x").pfValue,m=t.pstyle(f+"text-margin-y").pfValue,b=t.isEdge(),x=t.pstyle("text-halign").value,w=t.pstyle("text-valign").value;switch(b&&(x="center",w="center"),c+=y,d+=m,0!==(p=r?this.getTextAngle(t,n):0)&&(l=c,u=d,e.translate(l,u),e.rotate(p),c=0,d=0),w){case"top":break;case"center":d+=v/2;break;case"bottom":d+=v}var E=t.pstyle("text-background-opacity").value,k=t.pstyle("text-border-opacity").value,C=t.pstyle("text-border-width").pfValue,S=t.pstyle("text-background-padding").pfValue,P=t.pstyle("text-background-shape").strValue,D=0===P.indexOf("round"),T=2;if(E>0||C>0&&k>0){var _=c-S;switch(x){case"left":_-=g;break;case"center":_-=g/2}var M=d-v-S,B=g+2*S,N=v+2*S;if(E>0){var z=e.fillStyle,I=t.pstyle("text-background-color").value;e.fillStyle="rgba("+I[0]+","+I[1]+","+I[2]+","+E*s+")",D?Gu(e,_,M,B,N,T):e.fillRect(_,M,B,N),e.fillStyle=z}if(C>0&&k>0){var A=e.strokeStyle,L=e.lineWidth,O=t.pstyle("text-border-color").value,R=t.pstyle("text-border-style").value;if(e.strokeStyle="rgba("+O[0]+","+O[1]+","+O[2]+","+k*s+")",e.lineWidth=C,e.setLineDash)switch(R){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash([4,2]);break;case"double":e.lineWidth=C/4,e.setLineDash([]);break;case"solid":e.setLineDash([])}if(D?Gu(e,_,M,B,N,T,"stroke"):e.strokeRect(_,M,B,N),"double"===R){var V=C/2;D?Gu(e,_+V,M+V,B-2*V,N-2*V,T,"stroke"):e.strokeRect(_+V,M+V,B-2*V,N-2*V)}e.setLineDash&&e.setLineDash([]),e.lineWidth=L,e.strokeStyle=A}}var F=2*t.pstyle("text-outline-width").pfValue;if(F>0&&(e.lineWidth=F),"wrap"===t.pstyle("text-wrap").value){var j=Ue(o,"labelWrapCachedLines",n),q=Ue(o,"labelLineHeight",n),Y=g/2,X=this.getLabelJustification(t);switch("auto"===X||("left"===x?"left"===X?c+=-g:"center"===X&&(c+=-Y):"center"===x?"left"===X?c+=-Y:"right"===X&&(c+=Y):"right"===x&&("center"===X?c+=Y:"right"===X&&(c+=g))),w){case"top":d-=(j.length-1)*q;break;case"center":case"bottom":d-=(j.length-1)*q}for(var W=0;W0&&e.strokeText(j[W],c,d),e.fillText(j[W],c,d),d+=q}else F>0&&e.strokeText(h,c,d),e.fillText(h,c,d);0!==p&&(e.rotate(-p),e.translate(-l,-u))}}};var Uu={drawNode:function(e,t,n){var r,i,a=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],o=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],s=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],l=this,u=t._private,c=u.rscratch,d=t.position();if(x(d.x)&&x(d.y)&&(!s||t.visible())){var h,p,f=s?t.effectiveOpacity():1,g=l.usePaths(),v=!1,y=t.padding();r=t.width()+2*y,i=t.height()+2*y,n&&(p=n,e.translate(-p.x1,-p.y1));for(var m=t.pstyle("background-image"),b=m.value,w=new Array(b.length),E=new Array(b.length),k=0,C=0;C0&&void 0!==arguments[0]?arguments[0]:M;l.eleFillStyle(e,t,n)},H=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:R;l.colorStrokeStyle(e,B[0],B[1],B[2],t)},K=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q;l.colorStrokeStyle(e,F[0],F[1],F[2],t)},G=function(e,t,n,r){var i,a=l.nodePathCache=l.nodePathCache||[],o=_e("polygon"===n?n+","+r.join(","):n,""+t,""+e,""+X),s=a[o],u=!1;return null!=s?(i=s,u=!0,c.pathCache=i):(i=new Path2D,a[o]=c.pathCache=i),{path:i,cacheHit:u}},U=t.pstyle("shape").strValue,Z=t.pstyle("shape-polygon-points").pfValue;if(g){e.translate(d.x,d.y);var $=G(r,i,U,Z);h=$.path,v=$.cacheHit}var Q=function(){if(!v){var n=d;g&&(n={x:0,y:0}),l.nodeShapes[l.getNodeShape(t)].draw(h||e,n.x,n.y,r,i,X,c)}g?e.fill(h):e.fill()},J=function(){for(var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:f,r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=u.backgrounding,a=0,o=0;o0&&void 0!==arguments[0]&&arguments[0],a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:f;l.hasPie(t)&&(l.drawPie(e,t,a),n&&(g||l.nodeShapes[l.getNodeShape(t)].draw(e,d.x,d.y,r,i,X,c)))},te=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:f,n=(T>0?T:-T)*t,r=T>0?0:255;0!==T&&(l.colorFillStyle(e,r,r,r,n),g?e.fill(h):e.fill())},ne=function(){if(_>0){if(e.lineWidth=_,e.lineCap=I,e.lineJoin=z,e.setLineDash)switch(N){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash(L),e.lineDashOffset=O;break;case"solid":case"double":e.setLineDash([])}if("center"!==A){if(e.save(),e.lineWidth*=2,"inside"===A)g?e.clip(h):e.clip();else{var t=new Path2D;t.rect(-r/2-_,-i/2-_,r+2*_,i+2*_),t.addPath(h),e.clip(t,"evenodd")}g?e.stroke(h):e.stroke(),e.restore()}else g?e.stroke(h):e.stroke();if("double"===N){e.lineWidth=_/3;var n=e.globalCompositeOperation;e.globalCompositeOperation="destination-out",g?e.stroke(h):e.stroke(),e.globalCompositeOperation=n}e.setLineDash&&e.setLineDash([])}},re=function(){if(V>0){if(e.lineWidth=V,e.lineCap="butt",e.setLineDash)switch(j){case"dotted":e.setLineDash([1,1]);break;case"dashed":e.setLineDash([4,2]);break;case"solid":case"double":e.setLineDash([])}var n=d;g&&(n={x:0,y:0});var a=l.getNodeShape(t),o=_;"inside"===A&&(o=0),"outside"===A&&(o*=2);var s,u=(r+o+(V+Y))/r,c=(i+o+(V+Y))/i,h=r*u,p=i*c,f=l.nodeShapes[a].points;if(g)s=G(h,p,a,f).path;if("ellipse"===a)l.drawEllipsePath(s||e,n.x,n.y,h,p);else if(["round-diamond","round-heptagon","round-hexagon","round-octagon","round-pentagon","round-polygon","round-triangle","round-tag"].includes(a)){var v=0,y=0,m=0;"round-diamond"===a?v=1.4*(o+Y+V):"round-heptagon"===a?(v=1.075*(o+Y+V),m=-(o/2+Y+V)/35):"round-hexagon"===a?v=1.12*(o+Y+V):"round-pentagon"===a?(v=1.13*(o+Y+V),m=-(o/2+Y+V)/15):"round-tag"===a?(v=1.12*(o+Y+V),y=.07*(o/2+V+Y)):"round-triangle"===a&&(v=(o+Y+V)*(Math.PI/2),m=-(o+Y/2+V)/Math.PI),0!==v&&(h=r*(u=(r+v)/r),["round-hexagon","round-tag"].includes(a)||(p=i*(c=(i+v)/i)));for(var b=h/2,x=p/2,w=(X="auto"===X?rn(h,p):X)+(o+V+Y)/2,E=new Array(f.length/2),k=new Array(f.length/2),C=0;C0){if(r=r||n.position(),null==i||null==a){var d=n.padding();i=n.width()+2*d,a=n.height()+2*d}this.colorFillStyle(t,l[0],l[1],l[2],s),this.nodeShapes[u].draw(t,r.x,r.y,i+2*o,a+2*o,c),t.fill()}}}};Uu.drawNodeOverlay=Zu("overlay"),Uu.drawNodeUnderlay=Zu("underlay"),Uu.hasPie=function(e){return(e=e[0])._private.hasPie},Uu.drawPie=function(e,t,n,r){t=t[0],r=r||t.position();var i=t.cy().style(),a=t.pstyle("pie-size"),o=r.x,s=r.y,l=t.width(),u=t.height(),c=Math.min(l,u)/2,d=0;this.usePaths()&&(o=0,s=0),"%"===a.units?c*=a.pfValue:void 0!==a.pfValue&&(c=a.pfValue/2);for(var h=1;h<=i.pieBackgroundN;h++){var p=t.pstyle("pie-"+h+"-background-size").value,f=t.pstyle("pie-"+h+"-background-color").value,g=t.pstyle("pie-"+h+"-background-opacity").value*n,v=p/100;v+d>1&&(v=1-d);var y=1.5*Math.PI+2*Math.PI*d,m=y+2*Math.PI*v;0===p||d>=1||d+v>1||(e.beginPath(),e.moveTo(o,s),e.arc(o,s,c,y,m),e.closePath(),this.colorFillStyle(e,f[0],f[1],f[2],g),e.fill(),d+=v)}};var $u={};$u.getPixelRatio=function(){var e=this.data.contexts[0];if(null!=this.forcedPixelRatio)return this.forcedPixelRatio;var t=this.cy.window(),n=e.backingStorePixelRatio||e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return(t.devicePixelRatio||1)/n},$u.paintCache=function(e){for(var t,n=this.paintCaches=this.paintCaches||[],r=!0,i=0;io.minMbLowQualFrames&&(o.motionBlurPxRatio=o.mbPxRBlurry)),o.clearingMotionBlur&&(o.motionBlurPxRatio=1),o.textureDrawLastFrame&&!d&&(c[o.NODE]=!0,c[o.SELECT_BOX]=!0);var m=l.style(),b=l.zoom(),x=void 0!==i?i:b,w=l.pan(),E={x:w.x,y:w.y},k={zoom:b,pan:{x:w.x,y:w.y}},C=o.prevViewport;void 0===C||k.zoom!==C.zoom||k.pan.x!==C.pan.x||k.pan.y!==C.pan.y||g&&!f||(o.motionBlurPxRatio=1),a&&(E=a),x*=s,E.x*=s,E.y*=s;var S=o.getCachedZSortedEles();function P(e,t,n,r,i){var a=e.globalCompositeOperation;e.globalCompositeOperation="destination-out",o.colorFillStyle(e,255,255,255,o.motionBlurTransparency),e.fillRect(t,n,r,i),e.globalCompositeOperation=a}function D(e,r){var s,l,c,d;o.clearingMotionBlur||e!==u.bufferContexts[o.MOTIONBLUR_BUFFER_NODE]&&e!==u.bufferContexts[o.MOTIONBLUR_BUFFER_DRAG]?(s=E,l=x,c=o.canvasWidth,d=o.canvasHeight):(s={x:w.x*p,y:w.y*p},l=b*p,c=o.canvasWidth*p,d=o.canvasHeight*p),e.setTransform(1,0,0,1,0,0),"motionBlur"===r?P(e,0,0,c,d):t||void 0!==r&&!r||e.clearRect(0,0,c,d),n||(e.translate(s.x,s.y),e.scale(l,l)),a&&e.translate(a.x,a.y),i&&e.scale(i,i)}if(d||(o.textureDrawLastFrame=!1),d){if(o.textureDrawLastFrame=!0,!o.textureCache){o.textureCache={},o.textureCache.bb=l.mutableElements().boundingBox(),o.textureCache.texture=o.data.bufferCanvases[o.TEXTURE_BUFFER];var T=o.data.bufferContexts[o.TEXTURE_BUFFER];T.setTransform(1,0,0,1,0,0),T.clearRect(0,0,o.canvasWidth*o.textureMult,o.canvasHeight*o.textureMult),o.render({forcedContext:T,drawOnlyNodeLayer:!0,forcedPxRatio:s*o.textureMult}),(k=o.textureCache.viewport={zoom:l.zoom(),pan:l.pan(),width:o.canvasWidth,height:o.canvasHeight}).mpan={x:(0-k.pan.x)/k.zoom,y:(0-k.pan.y)/k.zoom}}c[o.DRAG]=!1,c[o.NODE]=!1;var _=u.contexts[o.NODE],M=o.textureCache.texture;k=o.textureCache.viewport;_.setTransform(1,0,0,1,0,0),h?P(_,0,0,k.width,k.height):_.clearRect(0,0,k.width,k.height);var B=m.core("outside-texture-bg-color").value,N=m.core("outside-texture-bg-opacity").value;o.colorFillStyle(_,B[0],B[1],B[2],N),_.fillRect(0,0,k.width,k.height);b=l.zoom();D(_,!1),_.clearRect(k.mpan.x,k.mpan.y,k.width/k.zoom/s,k.height/k.zoom/s),_.drawImage(M,k.mpan.x,k.mpan.y,k.width/k.zoom/s,k.height/k.zoom/s)}else o.textureOnViewport&&!t&&(o.textureCache=null);var z=l.extent(),I=o.pinching||o.hoverData.dragging||o.swipePanning||o.data.wheelZooming||o.hoverData.draggingEles||o.cy.animated(),A=o.hideEdgesOnViewport&&I,L=[];if(L[o.NODE]=!c[o.NODE]&&h&&!o.clearedForMotionBlur[o.NODE]||o.clearingMotionBlur,L[o.NODE]&&(o.clearedForMotionBlur[o.NODE]=!0),L[o.DRAG]=!c[o.DRAG]&&h&&!o.clearedForMotionBlur[o.DRAG]||o.clearingMotionBlur,L[o.DRAG]&&(o.clearedForMotionBlur[o.DRAG]=!0),c[o.NODE]||n||r||L[o.NODE]){var O=h&&!L[o.NODE]&&1!==p;D(_=t||(O?o.data.bufferContexts[o.MOTIONBLUR_BUFFER_NODE]:u.contexts[o.NODE]),h&&!O?"motionBlur":void 0),A?o.drawCachedNodes(_,S.nondrag,s,z):o.drawLayeredElements(_,S.nondrag,s,z),o.debug&&o.drawDebugPoints(_,S.nondrag),n||h||(c[o.NODE]=!1)}if(!r&&(c[o.DRAG]||n||L[o.DRAG])){O=h&&!L[o.DRAG]&&1!==p;D(_=t||(O?o.data.bufferContexts[o.MOTIONBLUR_BUFFER_DRAG]:u.contexts[o.DRAG]),h&&!O?"motionBlur":void 0),A?o.drawCachedNodes(_,S.drag,s,z):o.drawCachedElements(_,S.drag,s,z),o.debug&&o.drawDebugPoints(_,S.drag),n||h||(c[o.DRAG]=!1)}if(o.showFps||!r&&c[o.SELECT_BOX]&&!n){if(D(_=t||u.contexts[o.SELECT_BOX]),1==o.selection[4]&&(o.hoverData.selecting||o.touchData.selecting)){b=o.cy.zoom();var R=m.core("selection-box-border-width").value/b;_.lineWidth=R,_.fillStyle="rgba("+m.core("selection-box-color").value[0]+","+m.core("selection-box-color").value[1]+","+m.core("selection-box-color").value[2]+","+m.core("selection-box-opacity").value+")",_.fillRect(o.selection[0],o.selection[1],o.selection[2]-o.selection[0],o.selection[3]-o.selection[1]),R>0&&(_.strokeStyle="rgba("+m.core("selection-box-border-color").value[0]+","+m.core("selection-box-border-color").value[1]+","+m.core("selection-box-border-color").value[2]+","+m.core("selection-box-opacity").value+")",_.strokeRect(o.selection[0],o.selection[1],o.selection[2]-o.selection[0],o.selection[3]-o.selection[1]))}if(u.bgActivePosistion&&!o.hoverData.selecting){b=o.cy.zoom();var V=u.bgActivePosistion;_.fillStyle="rgba("+m.core("active-bg-color").value[0]+","+m.core("active-bg-color").value[1]+","+m.core("active-bg-color").value[2]+","+m.core("active-bg-opacity").value+")",_.beginPath(),_.arc(V.x,V.y,m.core("active-bg-size").pfValue/b,0,2*Math.PI),_.fill()}var F=o.lastRedrawTime;if(o.showFps&&F){F=Math.round(F);var j=Math.round(1e3/F);_.setTransform(1,0,0,1,0,0),_.fillStyle="rgba(255, 0, 0, 0.75)",_.strokeStyle="rgba(255, 0, 0, 0.75)",_.lineWidth=1,_.fillText("1 frame = "+F+" ms = "+j+" fps",0,20);_.strokeRect(0,30,250,20),_.fillRect(0,30,250*Math.min(j/60,1),20)}n||(c[o.SELECT_BOX]=!1)}if(h&&1!==p){var q=u.contexts[o.NODE],Y=o.data.bufferCanvases[o.MOTIONBLUR_BUFFER_NODE],X=u.contexts[o.DRAG],W=o.data.bufferCanvases[o.MOTIONBLUR_BUFFER_DRAG],H=function(e,t,n){e.setTransform(1,0,0,1,0,0),n||!y?e.clearRect(0,0,o.canvasWidth,o.canvasHeight):P(e,0,0,o.canvasWidth,o.canvasHeight);var r=p;e.drawImage(t,0,0,o.canvasWidth*r,o.canvasHeight*r,0,0,o.canvasWidth,o.canvasHeight)};(c[o.NODE]||L[o.NODE])&&(H(q,Y,L[o.NODE]),c[o.NODE]=!1),(c[o.DRAG]||L[o.DRAG])&&(H(X,W,L[o.DRAG]),c[o.DRAG]=!1)}o.prevViewport=k,o.clearingMotionBlur&&(o.clearingMotionBlur=!1,o.motionBlurCleared=!0,o.motionBlur=!0),h&&(o.motionBlurTimeout=setTimeout((function(){o.motionBlurTimeout=null,o.clearedForMotionBlur[o.NODE]=!1,o.clearedForMotionBlur[o.DRAG]=!1,o.motionBlur=!1,o.clearingMotionBlur=!d,o.mbFrames=0,c[o.NODE]=!0,c[o.DRAG]=!0,o.redraw()}),100)),t||l.emit("render")};for(var Qu={drawPolygonPath:function(e,t,n,r,i,a){var o=r/2,s=i/2;e.beginPath&&e.beginPath(),e.moveTo(t+o*a[0],n+s*a[1]);for(var l=1;l0&&a>0){h.clearRect(0,0,i,a),h.globalCompositeOperation="source-over";var p=this.getCachedZSortedEles();if(e.full)h.translate(-n.x1*l,-n.y1*l),h.scale(l,l),this.drawElements(h,p),h.scale(1/l,1/l),h.translate(n.x1*l,n.y1*l);else{var f=t.pan(),g={x:f.x*l,y:f.y*l};l*=t.zoom(),h.translate(g.x,g.y),h.scale(l,l),this.drawElements(h,p),h.scale(1/l,1/l),h.translate(-g.x,-g.y)}e.bg&&(h.globalCompositeOperation="destination-over",h.fillStyle=e.bg,h.rect(0,0,i,a),h.fill())}return d},ac.png=function(e){return sc(e,this.bufferCanvasImage(e),"image/png")},ac.jpg=function(e){return sc(e,this.bufferCanvasImage(e),"image/jpeg")};var lc={nodeShapeImpl:function(e,t,n,r,i,a,o,s){switch(e){case"ellipse":return this.drawEllipsePath(t,n,r,i,a);case"polygon":return this.drawPolygonPath(t,n,r,i,a,o);case"round-polygon":return this.drawRoundPolygonPath(t,n,r,i,a,o,s);case"roundrectangle":case"round-rectangle":return this.drawRoundRectanglePath(t,n,r,i,a,s);case"cutrectangle":case"cut-rectangle":return this.drawCutRectanglePath(t,n,r,i,a,o,s);case"bottomroundrectangle":case"bottom-round-rectangle":return this.drawBottomRoundRectanglePath(t,n,r,i,a,s);case"barrel":return this.drawBarrelPath(t,n,r,i,a)}}},uc=dc,cc=dc.prototype;function dc(e){var t=this,n=t.cy.window().document;t.data={canvases:new Array(cc.CANVAS_LAYERS),contexts:new Array(cc.CANVAS_LAYERS),canvasNeedsRedraw:new Array(cc.CANVAS_LAYERS),bufferCanvases:new Array(cc.BUFFER_COUNT),bufferContexts:new Array(cc.CANVAS_LAYERS)};t.data.canvasContainer=n.createElement("div");var r=t.data.canvasContainer.style;t.data.canvasContainer.style["-webkit-tap-highlight-color"]="rgba(0,0,0,0)",r.position="relative",r.zIndex="0",r.overflow="hidden";var i=e.cy.container();i.appendChild(t.data.canvasContainer),i.style["-webkit-tap-highlight-color"]="rgba(0,0,0,0)";var a={"-webkit-user-select":"none","-moz-user-select":"-moz-none","user-select":"none","-webkit-tap-highlight-color":"rgba(0,0,0,0)","outline-style":"none"};c&&c.userAgent.match(/msie|trident|edge/i)&&(a["-ms-touch-action"]="none",a["touch-action"]="none");for(var o=0;o{var explorer_templates_default={"explorer-head.mustache":` + + + + +{{{pageTitle}}} · {{{siteTitle}}} + + + + + +
+ {{{siteTitle}}} model explorer + + + +
+
+ +`,"explorer-foot.mustache":`
+
Built from explorer.json by the metaobjects docs-site generator{{#stamp}} · {{{stamp}}}{{/stamp}}. Static: no server, no LLM call.
+ +{{#needsGraph}}{{/needsGraph}} + + + +`,"explorer-card.mustache":`
+

{{{levelHtml}}}{{{linkHtml}}} {{{statusHtml}}}{{{verdictHtml}}}

+
{{{statement}}}
+
{{{barHtml}}}
{{{countsLine}}}
+ {{#hasChildren}}
    {{#children}}
  • {{{levelHtml}}}{{{linkHtml}}} {{{glyphHtml}}}
  • {{/children}}
{{/hasChildren}} +
Summary from the levels below
No summary is generated in this build.
+
+`,"explorer-overview.html.mustache":`

{{{heading}}}

+
Built from {{{sourcesLine}}}. Every number below is computed from the project's metadata or the gate's own output.
+
+{{#tiles}}
{{{n}}}
{{{l}}}
+{{/tiles}}
+{{#hasRequirements}}{{{legendHtml}}}{{/hasRequirements}} +{{#hasRequirements}} +

Features requirement.functional, by level

+{{#hasFeatures}}
+{{#featureCards}}{{> card}}{{/featureCards}} +
{{/hasFeatures}} +{{^hasFeatures}}
No requirement.functional is declared.
{{/hasFeatures}} +

Qualities requirement.architectural, the non-functional policies

+{{#hasQualities}}
+{{#qualityCards}}{{> card}}{{/qualityCards}} +
{{/hasQualities}} +{{^hasQualities}}
No requirement.architectural is declared.
{{/hasQualities}} +{{/hasRequirements}} +{{^hasRequirements}} +
This model declares no requirements yet, so this page cannot say what each part is for. Declare requirement.functional entries (levels 1 to 3 for the problem, 4 and 5 naming the model) and this page opens on them, with every entity traced to the feature it serves.
+{{/hasRequirements}} +

Packages what the model holds

+
+{{#packageCards}}

{{{name}}}

{{{kindLineHtml}}}
{{{membersHtml}}}
+{{/packageCards}}
+`,"explorer-map.html.mustache":`

Model map

+
Entities and the references between them. A slice is the set of model nodes a requirement subtree claims, a package holds, or a prompt reads and returns.
+
+ + + + + + + +
+
Click a node to see why it exists, what it holds and what was generated from it. Double-click to open its page.
+
+ +`,"explorer-object.html.mustache":`
{{{crumbsHtml}}}
+

{{{name}}} {{#isAbstract}}abstract{{/isAbstract}}{{#isReadOnly}}read-only view{{/isReadOnly}}{{#isUnclaimed}}unclaimed{{/isUnclaimed}}

+ +{{#description}}
{{{description}}}
{{/description}} +
{{{kindLabel}}} · {{{storageLine}}}{{#extendsHtml}} · extends {{{extendsHtml}}}{{/extendsHtml}}
+
+
+

Why it exists

+ {{#hasWhy}}
+ {{#whyRows}} + {{/whyRows}}
CapabilityRequirementLevelStatusOn
{{{capabilityHtml}}}{{{reqHtml}}}
{{{statement}}}
{{{levelHtml}}}{{{statusHtml}}}{{{onHtml}}}
{{/hasWhy}} + {{^hasWhy}}
{{{whyEmptyHtml}}}
{{/hasWhy}} + {{#projection}} +

Read model

+
+ {{#basesHtml}}
Surfaces fields of {{{basesHtml}}}.
{{/basesHtml}} + {{#hasOrigins}}
{{#origins}}{{/origins}}
FieldOriginDefinition
{{{field}}}{{{origin}}}{{{definitionHtml}}}
{{/hasOrigins}} +
+ {{/projection}} + {{#report}} +

Report

+
+ {{#fromHtml}}{{/fromHtml}} + {{#spineHtml}}{{/spineHtml}} + {{#dimensionsHtml}}{{/dimensionsHtml}} + {{#measuresHtml}}{{/measuresHtml}} + {{#segmentHtml}}{{/segmentHtml}} + {{#filterHtml}}{{/filterHtml}} +
From{{{fromHtml}}}
Spine{{{spineHtml}}}
Dimensions{{{dimensionsHtml}}}
Measures{{{measuresHtml}}}
Segment{{{segmentHtml}}}
Filter{{{filterHtml}}}
+ {{/report}} + {{#hasFields}}

Fields

+
{{#hasColumn}}{{/hasColumn}}{{#showClaims}}{{/showClaims}} + {{#fields}}{{#hasColumn}}{{/hasColumn}}{{#showClaims}}{{/showClaims}} + {{/fields}}
FieldTypeColumnFlagsClaimed at L5
{{{name}}} {{{inheritedHtml}}}{{{type}}}{{{refHtml}}}{{{valuesHtml}}}{{{column}}}{{{flagsHtml}}}{{{claimsHtml}}}
{{/hasFields}} + {{#hasKeys}}

Keys and references

+
{{#keys}}{{/keys}}
{{{kind}}} {{{name}}} {{{inheritedHtml}}}{{{shape}}}{{{targetHtml}}}
{{/hasKeys}} + {{#hasReporting}}

Reporting vocabulary

+
{{#reporting}}{{/reporting}}
NameKindDefinition
{{{name}}}{{{kind}}}{{{definitionHtml}}}
{{/hasReporting}} + {{#hasLayouts}}

Screens declared

{{#layouts}}
{{{kind}}} {{{name}}}{{#detailHtml}}: {{{detailHtml}}}{{/detailHtml}}
{{/layouts}}{{/hasLayouts}} +
+ +
+`,"explorer-node.html.mustache":`
{{{crumbsHtml}}}
+

{{{name}}} {{#isAbstract}}abstract{{/isAbstract}}

+ +{{#description}}
{{{description}}}
{{/description}} +
{{{kindLabel}}}{{#extendsHtml}} · extends {{{extendsHtml}}}{{/extendsHtml}}
+
+
+

Why it exists

+ {{#hasWhy}}
+ {{#whyRows}} + {{/whyRows}}
CapabilityRequirementLevelStatusOn
{{{capabilityHtml}}}{{{reqHtml}}}
{{{statement}}}
{{{levelHtml}}}{{{statusHtml}}}{{{onHtml}}}
{{/hasWhy}} + {{^hasWhy}}
{{{whyEmptyHtml}}}
{{/hasWhy}} + {{#hasAttrs}}

Attributes

+
{{#attrs}}{{/attrs}}
@{{{name}}}{{{valueHtml}}}
{{/hasAttrs}} + {{#hasMembers}}

Members

+
+ {{#members}} + {{/members}}
NameTypeAttributes
{{{nameHtml}}}{{#below}} +{{below}}{{/below}}{{{kind}}}{{{attrsHtml}}}
{{/hasMembers}} +
+ +
+`,"explorer-prompt.html.mustache":`
{{{crumbsHtml}}}
+

{{{name}}} {{#isUnclaimed}}unclaimed{{/isUnclaimed}}

+ +{{#description}}
{{{description}}}
{{/description}} +
{{{attrsHtml}}}
+
+
+

Payload: {{{payloadHtml}}}

+ {{#hasPayload}}
{{#payloadRows}}{{/payloadRows}}
FieldTypeUsed in text
{{{name}}} {{{requiredHtml}}}{{{type}}}{{{refHtml}}}{{{usedHtml}}}
{{/hasPayload}} + {{^hasPayload}}
No payload: the text renders from nothing typed.
{{/hasPayload}} +

Reply: {{{replyHtml}}}

+ {{#hasReply}}
{{#replyRows}}{{/replyRows}}
FieldType
{{{name}}}{{{type}}}{{{valuesHtml}}}
{{/hasReply}} + {{^hasReply}}
Outbound only: no reply parser.
{{/hasReply}} +

Why it exists

+ {{#hasWhy}}
{{#whyRows}}{{/whyRows}}
CapabilityRequirementLevelStatus
{{{capabilityHtml}}}{{{reqHtml}}}
{{{statement}}}
{{{levelHtml}}}{{{statusHtml}}}
{{/hasWhy}} + {{^hasWhy}}
{{{whyEmptyHtml}}}
{{/hasWhy}} +
+
+

Text {{{textMeta}}}

+ {{#hasText}}
{{{textHtml}}}
{{/hasText}} + {{^hasText}}
The text {{{textRef}}} was not found beside the model, so this page cannot show it.
{{/hasText}} +

Generated

+ {{#hasGenerated}}{{#generated}}
{{{generator}}}{{#files}}
{{{.}}}
{{/files}}
{{/generated}}{{/hasGenerated}} + {{^hasGenerated}}
{{{generatedNote}}}
{{/hasGenerated}} +
Proven today: meta verify --templates fails if the text names a variable the payload lacks. This page shows the other direction too: payload fields the text never uses.
+
+
+`,"explorer-prompts.html.mustache":`

Prompts

+
Each declared template, its typed payload, its reply type, and the requirements that claim it.
+{{#hasRows}}
+{{#rows}} +{{/rows}}
TemplatePayloadReplyClaimed by
{{{linkHtml}}} {{{kind}}}{{#description}}
{{{description}}}
{{/description}}
{{{payloadHtml}}}{{{replyHtml}}}{{{claimsHtml}}}
{{/hasRows}} +{{^hasRows}}
This model declares no template.*.
{{/hasRows}} +`,"explorer-requirements.html.mustache":`

Requirements

+
Hierarchy is nesting. L1 to L3 describe the problem; only L4 (an object or prompt) and L5 (a member) may name the model.
+ +{{{legendHtml}}} +{{#hasTree}}
{{{treeHtml}}}
{{/hasTree}} +{{^hasTree}}
{{{emptyNote}}}
{{/hasTree}} +`,"explorer-requirement.html.mustache":`
{{{crumbsHtml}}}
+

{{{levelHtml}}}{{{name}}} {{{statusHtml}}}{{{dispositionHtml}}}{{{verdictHtml}}}

+ +
{{{address}}}
+
+
+

Statement

{{{statement}}}

Counterexample

{{{counterexample}}}{{#hasDescription}}

Scope

{{{description}}}
{{/hasDescription}}
+

Implemented by

+ {{#hasLinks}}
{{#linkRows}}{{/linkRows}}
ReferenceKindResolves
{{{refHtml}}}{{{kind}}}{{{resolvesHtml}}}
{{/hasLinks}} + {{^hasLinks}}
{{{linksEmpty}}}
{{/hasLinks}} + {{#hasBelow}}

Below ({{childCount}}){{#deeper}} {{belowCount}} in all{{/deeper}}

{{{belowBarHtml}}}
    {{#children}}
  • {{{levelHtml}}}{{{linkHtml}}} {{{statusHtml}}}
  • {{/children}}
{{/hasBelow}} +
{{#sliceHref}}Show this slice on the model map{{/sliceHref}}{{#sliceHref}}{{#traceHref}} · {{/traceHref}}{{/sliceHref}}{{#traceHref}}Trace to code{{/traceHref}}
+
+
+

What the build proves about this entry

+
{{#proof}}{{/proof}}
{{{what}}}{{{verdictHtml}}}{{{howHtml}}}
+ {{#trackedHtml}}

Tracked by

{{{trackedHtml}}}{{/trackedHtml}} + {{#digest}}

Statement digest

{{{digest}}}
Moves when the statement changes; a summary of this entry would be pinned to it.
{{/digest}} +
+
+`,"explorer-matrix.html.mustache":`

Traceability matrix

+
Rows are requirements that name the model; columns are stored entities and prompts, most claimed first. An empty column is a node nothing claims; a cell's colour and glyph are the row's declared status.
+{{#hasRows}}
{{{legendHtml}}}
+
{{{tableHtml}}}
{{/hasRows}} +{{^hasRows}}
{{#hasRequirements}}No requirement names the model yet: only L4 and L5 entries do.{{/hasRequirements}}{{^hasRequirements}}This model declares no requirements, so there is nothing to trace.{{/hasRequirements}}
{{/hasRows}} +`,"explorer-trace.html.mustache":`

Trace

+
From intent to code: requirement levels, then the model nodes they name, then the files generated from those nodes.
+{{#hasStarts}}
+ +
Hand-written modules that import the generated files are not scanned in this build, so the trace stops at the generated files. Click a requirement or a model node to open its page.
{{/hasStarts}} +{{^hasStarts}}
This model declares no requirements, so there is nothing to trace from. Every object's generated files are listed on its own page.
{{/hasStarts}} +`,"explorer-gaps.html.mustache":`

Gaps

+
What the model and the gate can already point at. Each card says whether it comes from the shipped gate or is a check this explorer adds.
+
+{{#cards}}

{{{title}}} {{{count}}} {{{source}}}

{{{whyHtml}}}
{{{bodyHtml}}}
+{{/cards}}
+`,"explorer-api.html.mustache":`

API

+{{#recorded}}
Every route the generated code mounts, by the object it serves: {{{summary}}}.
+{{#hasGroups}}
{{#groups}}

{{{linkHtml}}} {{{kind}}}{{#isReadOnly}} read-only{{/isReadOnly}}

{{#routes}}
{{{method}}} {{{path}}}
{{/routes}}
{{/groups}}
{{/hasGroups}} +{{^hasGroups}}
The run generated no routes.
{{/hasGroups}}{{/recorded}} +{{^recorded}}
The run that built this site recorded no routes: it generated none, or ran without the routes generator.
{{/recorded}} +`,"explorer-model.html.mustache":`

Packages

+
Every package in the model and what it declares.
+
+{{#packageCards}}

{{{name}}}

{{{kindLineHtml}}}
{{{membersHtml}}}
+{{/packageCards}}
+`,"explorer-package.html.mustache":`
{{{crumbsHtml}}}
+

{{{name}}}

+
+{{#rows}} +{{/rows}}
NameKindStorageFieldsClaim
{{{linkHtml}}} {{{abstractHtml}}}{{#description}}
{{{description}}}
{{/description}}
{{{kind}}}{{{storage}}}{{fieldCount}}{{{statusHtml}}}
+`};/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */var objectToString=Object.prototype.toString,isArray=Array.isArray||function(object){return objectToString.call(object)==="[object Array]"};function isFunction(object){return typeof object==="function"}function typeStr(obj){return isArray(obj)?"array":typeof obj}function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(obj,propName){return obj!=null&&typeof obj==="object"&&propName in obj}function primitiveHasOwnProperty(primitive,propName){return primitive!=null&&typeof primitive!=="object"&&primitive.hasOwnProperty&&primitive.hasOwnProperty(propName)}var regExpTest=RegExp.prototype.test;function testRegExp(re,string){return regExpTest.call(re,string)}var nonSpaceRe=/\S/;function isWhitespace(string){return!testRegExp(nonSpaceRe,string)}var entityMap={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function escapeHtml(string){return String(string).replace(/[&<>"'`=\/]/g,function(s){return entityMap[s]})}var whiteRe=/\s*/,spaceRe=/\s+/,equalsRe=/\s*=/,curlyRe=/\s*\}/,tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate(template,tags){if(!template)return[];var lineHasNonSpace=!1,sections=[],tokens=[],spaces=[],hasTag=!1,nonSpace=!1,indentation="",tagIndex=0;function stripSpace(){if(hasTag&&!nonSpace)while(spaces.length)delete tokens[spaces.pop()];else spaces=[];hasTag=!1,nonSpace=!1}var openingTagRe,closingTagRe,closingCurlyRe;function compileTags(tagsToCompile){if(typeof tagsToCompile==="string")tagsToCompile=tagsToCompile.split(spaceRe,2);if(!isArray(tagsToCompile)||tagsToCompile.length!==2)throw Error("Invalid tags: "+tagsToCompile);openingTagRe=new RegExp(escapeRegExp(tagsToCompile[0])+"\\s*"),closingTagRe=new RegExp("\\s*"+escapeRegExp(tagsToCompile[1])),closingCurlyRe=new RegExp("\\s*"+escapeRegExp("}"+tagsToCompile[1]))}compileTags(tags||mustache.tags);var scanner=new Scanner(template),start,type,value,chr,token,openSection;while(!scanner.eos()){if(start=scanner.pos,value=scanner.scanUntil(openingTagRe),value)for(var i=0,valueLength=value.length;i")token=[type,value,start,scanner.pos,indentation,tagIndex,lineHasNonSpace];else token=[type,value,start,scanner.pos];if(tagIndex++,tokens.push(token),type==="#"||type==="^")sections.push(token);else if(type==="/"){if(openSection=sections.pop(),!openSection)throw Error('Unopened section "'+value+'" at '+start);if(openSection[1]!==value)throw Error('Unclosed section "'+openSection[1]+'" at '+start)}else if(type==="name"||type==="{"||type==="&")nonSpace=!0;else if(type==="=")compileTags(value)}if(stripSpace(),openSection=sections.pop(),openSection)throw Error('Unclosed section "'+openSection[1]+'" at '+scanner.pos);return nestTokens(squashTokens(tokens))}function squashTokens(tokens){var squashedTokens=[],token,lastToken;for(var i=0,numTokens=tokens.length;i0?sections[sections.length-1][4]:nestedTokens;break;default:collector.push(token)}return nestedTokens}function Scanner(string){this.string=string,this.tail=string,this.pos=0}Scanner.prototype.eos=function(){return this.tail===""};Scanner.prototype.scan=function(re){var match=this.tail.match(re);if(!match||match.index!==0)return"";var string=match[0];return this.tail=this.tail.substring(string.length),this.pos+=string.length,string};Scanner.prototype.scanUntil=function(re){var index=this.tail.search(re),match;switch(index){case-1:match=this.tail,this.tail="";break;case 0:match="";break;default:match=this.tail.substring(0,index),this.tail=this.tail.substring(index)}return this.pos+=match.length,match};function Context(view,parentContext){this.view=view,this.cache={".":this.view},this.parent=parentContext}Context.prototype.push=function(view){return new Context(view,this)};Context.prototype.lookup=function(name){var cache=this.cache,value;if(cache.hasOwnProperty(name))value=cache[name];else{var context=this,intermediateValue,names,index,lookupHit=!1;while(context){if(name.indexOf(".")>0){intermediateValue=context.view,names=name.split("."),index=0;while(intermediateValue!=null&&index")value=this.renderPartial(token,context,partials,config);else if(symbol==="&")value=this.unescapedValue(token,context);else if(symbol==="name")value=this.escapedValue(token,context,config);else if(symbol==="text")value=this.rawValue(token);if(value!==void 0)buffer+=value}return buffer};Writer.prototype.renderSection=function(token,context,partials,originalTemplate,config){var self=this,buffer="",value=context.lookup(token[1]);function subRender(template){return self.render(template,context,partials,config)}if(!value)return;if(isArray(value))for(var j=0,valueLength=value.length;j0||!lineHasNonSpace))partialByNl[i]=filteredIndentation+partialByNl[i];return partialByNl.join(` +`)};Writer.prototype.renderPartial=function(token,context,partials,config){if(!partials)return;var tags=this.getConfigTags(config),value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null){var lineHasNonSpace=token[6],tagIndex=token[5],indentation=token[4],indentedValue=value;if(tagIndex==0&&indentation)indentedValue=this.indentPartial(value,indentation,lineHasNonSpace);var tokens=this.parse(indentedValue,tags);return this.renderTokens(tokens,context,partials,indentedValue,config)}};Writer.prototype.unescapedValue=function(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function(token,context,config){var escape=this.getConfigEscape(config)||mustache.escape,value=context.lookup(token[1]);if(value!=null)return typeof value==="number"&&escape===mustache.escape?String(value):escape(value)};Writer.prototype.rawValue=function(token){return token[1]};Writer.prototype.getConfigTags=function(config){if(isArray(config))return config;else if(config&&typeof config==="object")return config.tags;else return};Writer.prototype.getConfigEscape=function(config){if(config&&typeof config==="object"&&!isArray(config))return config.escape;else return};var mustache={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(cache){defaultWriter.templateCache=cache},get templateCache(){return defaultWriter.templateCache}},defaultWriter=new Writer;mustache.clearCache=function(){return defaultWriter.clearCache()};mustache.parse=function(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function(template,view,partials,config){if(typeof template!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+typeStr(template)+'" was given as the first argument for mustache#render(template, view, partials)');return defaultWriter.render(template,view,partials,config)};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer;var mustache_default=mustache;var xml=(s)=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),STRICT_NUMERIC=/^-?[0-9]+(\.[0-9]+)?$/,injectionGuard=(s)=>/^[=+\-@\t\r]/.test(s)&&!STRICT_NUMERIC.test(s)?"'"+s:s,csv=(s)=>{let v=injectionGuard(s);return/[",\n\r]/.test(v)?`"${v.replace(/"/g,'""')}"`:v},json=(s)=>JSON.stringify(s).slice(1,-1),raw=(s)=>s,ESCAPERS={text:raw,markdown:raw,html:xml,xml,json,csv,spreadsheet:(s)=>injectionGuard(xml(s))};var HAS_PREFIX="has";function hasAccessorName(fieldName){return"has"+capitalize(fieldName)}var LAST_ACCESSOR="-last";function capitalize(s){if(s.length===0)return s;let c0=s.charAt(0);if(c0===c0.toUpperCase()&&c0!==c0.toLowerCase())return s;return c0.toUpperCase()+s.slice(1)}function accessorValue(value){if(value===null||value===void 0)return!1;if(typeof value==="string")return value.trim().length>0;if(Array.isArray(value))return value.length>0;if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint")return;return typeof value==="object"}function withDerivedAccessors(payload,depth=0){return derive(payload,depth,void 0)}function derive(payload,depth,last){if(depth>32)return payload;if(Array.isArray(payload)){let end=payload.length-1;return payload.map((v,i)=>derive(v,depth+1,i===end))}if(payload===null||typeof payload!=="object")return payload;let proto=Object.getPrototypeOf(payload);if(proto!==Object.prototype&&proto!==null)return typedView(payload,depth,last);let src=payload,out={};for(let[k,v]of Object.entries(src))out[k]=derive(v,depth+1,void 0);for(let[k,v]of Object.entries(src)){let name=hasAccessorName(k);if(Object.prototype.hasOwnProperty.call(src,name))continue;let derived=accessorValue(v);if(derived!==void 0)out[name]=derived}if(last!==void 0&&!Object.prototype.hasOwnProperty.call(src,LAST_ACCESSOR))out[LAST_ACCESSOR]=last;return out}function decapitalize(s){return s.length===0?s:s.charAt(0).toLowerCase()+s.slice(1)}function typedView(target,depth,last){let members=new Map,member=(key)=>{if(members.has(key))return members.get(key);let raw2=Reflect.get(target,key,target),value=typeof raw2==="function"?(...args)=>derive(Reflect.apply(raw2,target,args),depth+1,void 0):derive(raw2,depth+1,void 0);return members.set(key,value),value},derived=(key)=>{if(typeof key!=="string")return;if(key===LAST_ACCESSOR)return last;if(!key.startsWith("has"))return;let rest=key.slice(3);for(let field of[decapitalize(rest),rest]){if(!(field in target)||hasAccessorName(field)!==key)continue;let raw2=Reflect.get(target,field,target);if(typeof raw2==="function")continue;let value=accessorValue(raw2);if(value!==void 0)return value}return};return new Proxy(Object.create(null),{has:(_stand,key)=>(key in target)||derived(key)!==void 0,get:(_stand,key)=>(key in target)?member(key):derived(key)})}var TEMPLATE_ENGINES=["mustache","jinja"],TEMPLATE_ENGINE_MUSTACHE="mustache",TEMPLATE_ENGINE_JINJA="jinja";var JINJA_EXTENSIONS=[".jinja",".j2",".jinja2"];function partialEngineMismatch(provider,ref,including){let known=provider.engineOf?.(ref);return known!==void 0&&known!==including}function partialEngineMessage(ref,including){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${ref} is not a ${including} template; a ${including} body includes only ${including} partials`}function templateEngineOf(provider,ref,explicit){if(explicit!==void 0){if(!TEMPLATE_ENGINES.includes(explicit))throw Error(`unknown template engine ${JSON.stringify(explicit)}; expected one of ${TEMPLATE_ENGINES.join(", ")}`);return explicit}if(provider!==void 0&&ref!==void 0){let known=provider.engineOf?.(ref);if(known!==void 0)return known}return"mustache"}var ERR_VAR_NOT_ON_PAYLOAD="ERR_VAR_NOT_ON_PAYLOAD",ERR_PARTIAL_UNRESOLVED="ERR_PARTIAL_UNRESOLVED",ERR_REQUIRED_SLOT_UNUSED="ERR_REQUIRED_SLOT_UNUSED";var ERR_TEMPLATE_NOT_STATIC="ERR_TEMPLATE_NOT_STATIC",ERR_TEMPLATE_SYNTAX="ERR_TEMPLATE_SYNTAX",ERR_TEMPLATE_ENGINE_UNSUPPORTED="ERR_TEMPLATE_ENGINE_UNSUPPORTED",MAX_DEPTH=32,TAG_OPEN_DELIMS=new Set([">"," ","\t",` +`,"\r"]);function hasOpenTag(text,tag){let needle=`<${tag}`;for(let i=text.indexOf(needle);i!==-1;i=text.indexOf(needle,i+1)){let next=text[i+needle.length];if(next!==void 0&&TAG_OPEN_DELIMS.has(next))return!0}return!1}function hasCloseTag(text,tag){return text.includes(``)}function slotAndTagFindings(referencedAtRoot,staticTexts,opts){let errors=[];for(let slot of opts?.requiredSlots??[])if(!referencedAtRoot.has(slot))errors.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:slot});let requiredTags=opts?.requiredTags??[];if(requiredTags.length>0){let haystack=staticTexts.join(` +`);for(let tag of requiredTags)if(!hasOpenTag(haystack,tag)||!hasCloseTag(haystack,tag))errors.push({code:"ERR_OUTPUT_TAG_MISSING",path:tag})}return errors}var unavailable=()=>{throw Error("the explorer app renders Mustache only")},nunjucks_default=new Proxy({},{get:()=>unavailable});var internals=nunjucks_default;function parseJinja(text){return internals.parser.parse(text)}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.typename==="string"}function childNodes(node){let out=[],push2=(v)=>{if(Array.isArray(v))v.forEach(push2);else if(isNode(v))out.push(v)};for(let f of node.fields)push2(node[f]);if(node.typename==="Set")push2(node.body);return out}function refOfTemplateName(name){for(let ext of JINJA_EXTENSIONS)if(name.toLowerCase().endsWith(ext))return name.slice(0,-ext.length);return name}function safeCapture(original){return function(node,frame){this._emit("runtime.markSafe("),original.call(this,node,frame),this._emit(")")}}function environment(provider){let loader={getSource(name){let src=provider.resolve(refOfTemplateName(name));return src===void 0?null:{src,path:name,noCache:!0}}};return new nunjucks_default.Environment(loader,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function ensureDefinedOnly(value){if(value===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD}`);return value}function renderJinjaText(text,context,provider,escaper){let env=environment(provider),compiler=internals.compiler.Compiler.prototype,prevEscape=internals.lib.escape,prevCapture=compiler.compileCapture,prevEnsure=internals.runtime.ensureDefined;internals.runtime.ensureDefined=ensureDefinedOnly,internals.lib.escape=(v)=>escaper(typeof v==="string"?v:String(v)),compiler.compileCapture=safeCapture(prevCapture);try{return env.renderString(text,context)}finally{internals.lib.escape=prevEscape,compiler.compileCapture=prevCapture,internals.runtime.ensureDefined=prevEnsure}}var OPAQUE={tag:"opaque"},JINJA_GLOBALS=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),ELEMENT_FILTERS=new Set(["first","last","random"]),SAME_SHAPE_FILTERS=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),ATTRIBUTE_ARG_INDEX=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),ATTRIBUTE_KWARG="attribute";function typedOf(field,path){return{tag:"typed",fields:field.fields,isArray:field.isArray===!0,path}}function elementOf(v,path){if(v.tag==="opaque")return OPAQUE;return{tag:"typed",fields:v.isArray?v.fields:void 0,isArray:!1,path}}function segmentText(s){if(s.kind==="key")return`.${s.key}`;if(s.kind==="index")return`[${s.index}]`;return"[*]"}function verifyJinja(templateText,fields,opts){let errors=[],provider=opts?.provider,referencedAtRoot=new Set,staticTexts=[templateText],report=(code,path)=>{errors.push({code,path})};function lookupName(name,scope){for(let i=scope.frames.length-1;i>=0;i--){let hit=scope.frames[i].get(name);if(hit!==void 0)return hit}let field=scope.root.find((f)=>f.name===name);if(field!==void 0){if(scope.root===fields)referencedAtRoot.add(name);return typedOf(field,name)}return JINJA_GLOBALS.has(name)?OPAQUE:void 0}function bind(scope,name,value){scope.frames[scope.frames.length-1].set(name,value)}function pushFrame(scope){return{...scope,frames:[...scope.frames,new Map]}}function chainOf(node){let segments=[],cur=node;while(cur.typename==="LookupVal"){let val=cur.val;if(val.typename==="Literal"&&typeof val.value==="string")segments.unshift({kind:"key",key:val.value});else if(val.typename==="Literal"&&typeof val.value==="number")segments.unshift({kind:"index",index:val.value});else segments.unshift({kind:"dynamic",node:val});cur=cur.target}return{base:cur,segments}}function evalChain(node,scope){let{base,segments}=chainOf(node);for(let s of segments)if(s.kind==="dynamic")evalExpr(s.node,scope);let value,path;if(base.typename==="Symbol"){path=base.value;let fullPath2=path+segments.map(segmentText).join(""),hit=lookupName(path,scope);if(hit===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath2),OPAQUE;value=hit}else value=evalExpr(base,scope),path=value.tag==="typed"?value.path:"";let fullPath=path+segments.map(segmentText).join("");for(let s of segments){if(value.tag==="opaque")return OPAQUE;if(path+=segmentText(s),s.kind==="key"){let child=value.isArray?void 0:value.fields?.find((f)=>f.name===s.key);if(child===void 0)return report(ERR_VAR_NOT_ON_PAYLOAD,fullPath),OPAQUE;value=typedOf(child,path)}else if(value.isArray)value={tag:"typed",fields:value.fields,isArray:!1,path};else if(s.kind==="dynamic"&&value.fields!==void 0)return report(ERR_TEMPLATE_NOT_STATIC,fullPath),OPAQUE;else value={tag:"typed",fields:value.fields,isArray:!1,path}}return value}function checkAttributeName(receiver,attrNode,scope){if(receiver.tag==="opaque"){evalExpr(attrNode,scope);return}if(attrNode.typename!=="Literal"||typeof attrNode.value!=="string"){evalExpr(attrNode,scope),report(ERR_TEMPLATE_NOT_STATIC,`${receiver.path}[*]`);return}let attr=attrNode.value,current=receiver.fields;for(let seg of attr.split(".")){let hit=current?.find((f)=>f.name===seg);if(hit===void 0){report(ERR_VAR_NOT_ON_PAYLOAD,`${receiver.path}.${attr}`);return}current=hit.fields}}function splitArgs(args){let positional=[],keywords=[];for(let a of args===void 0?[]:childNodes(args))if(a.typename==="KeywordArgs")for(let pair of childNodes(a)){let key=pair.key;keywords.push([String(key.value),pair.value])}else positional.push(a);return{positional,keywords}}function evalFilter(node,scope){let name=String(node.name.value),{positional,keywords}=splitArgs(node.args),[subject,...rest]=positional,receiver=subject===void 0?OPAQUE:evalExpr(subject,scope);rest.forEach((a,i)=>{if(i===ATTRIBUTE_ARG_INDEX.get(name))checkAttributeName(receiver,a,scope);else evalExpr(a,scope)});for(let[key,value]of keywords)if(key===ATTRIBUTE_KWARG)checkAttributeName(receiver,value,scope);else evalExpr(value,scope);if(ELEMENT_FILTERS.has(name))return receiver.tag==="typed"?elementOf(receiver,`${receiver.path}|${name}`):OPAQUE;if(SAME_SHAPE_FILTERS.has(name))return receiver;return OPAQUE}function evalCall(node,scope){let callee=node.name;if(callee.typename==="LookupVal")evalExpr(callee.target,scope);else if(callee.typename==="Symbol"){let name=callee.value;if(lookupName(name,scope)===void 0)report(ERR_VAR_NOT_ON_PAYLOAD,name)}else evalExpr(callee,scope);let{positional,keywords}=splitArgs(node.args);return positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope)),OPAQUE}function walkCallable(node,scope){let inner=pushFrame(scope);for(let local of["caller","varargs","kwargs"])bind(inner,local,OPAQUE);for(let arg of childNodes(node.args))if(arg.typename==="Symbol")bind(inner,arg.value,OPAQUE);else if(arg.typename==="KeywordArgs")for(let pair of childNodes(arg))evalExpr(pair.value,scope),bind(inner,String(pair.key.value),OPAQUE);walk(node.body,inner)}function followTemplate(keyword,templateNode,scope,into,ignoreMissing=!1){if(templateNode.typename!=="Literal"||typeof templateNode.value!=="string"){evalExpr(templateNode,scope),report(ERR_TEMPLATE_NOT_STATIC,keyword);return}if(provider===void 0)return;let ref=refOfTemplateName(templateNode.value);if(scope.seen.includes(ref)||scope.seen.length>=MAX_DEPTH)return;let text=provider.resolve(ref);if(text===void 0){if(!ignoreMissing)report(ERR_PARTIAL_UNRESOLVED,ref);return}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA)){report(ERR_TEMPLATE_ENGINE_UNSUPPORTED,ref);return}staticTexts.push(text);let ast2;try{ast2=parseJinja(text)}catch(e){report(ERR_TEMPLATE_SYNTAX,`${ref}: ${e.message}`);return}walk(ast2,into(scope,ref))}function bindTarget(target,value,scope){if(target.typename==="Symbol")bind(scope,target.value,value);else for(let t of childNodes(target))bindTarget(t,OPAQUE,scope)}function evalExpr(node,scope){switch(node.typename){case"Symbol":case"LookupVal":return evalChain(node,scope);case"Literal":case"TemplateData":return OPAQUE;case"Group":{let kids=childNodes(node);if(kids.length===1)return evalExpr(kids[0],scope);return kids.forEach((k)=>evalExpr(k,scope)),OPAQUE}case"Filter":case"FilterAsync":return evalFilter(node,scope);case"FunCall":return evalCall(node,scope);case"Caller":return walkCallable(node,scope),OPAQUE;case"Is":{evalExpr(node.left,scope);let test=node.right;if(test.typename==="FunCall"){let{positional,keywords}=splitArgs(test.args);positional.forEach((a)=>evalExpr(a,scope)),keywords.forEach(([,v])=>evalExpr(v,scope))}return OPAQUE}case"Pair":{let key=node.key;if(key.typename!=="Symbol")evalExpr(key,scope);return evalExpr(node.value,scope),OPAQUE}case"Capture":return walk(node.body,scope),OPAQUE;default:for(let child of childNodes(node))evalExpr(child,scope);return OPAQUE}}function walk(node,scope){switch(node.typename){case"Root":case"NodeList":for(let child of childNodes(node))walk(child,scope);return;case"Output":for(let child of childNodes(node))evalExpr(child,scope);return;case"If":case"IfAsync":{if(evalExpr(node.cond,scope),walk(node.body,scope),isNode(node.else_))walk(node.else_,scope);return}case"For":case"AsyncEach":case"AsyncAll":{let iterable=evalExpr(node.arr,scope),inner=pushFrame(scope);bind(inner,"loop",OPAQUE);let target=node.name;if(target.typename==="Symbol"){let name=target.value;bind(inner,name,elementOf(iterable,name))}else bindTarget(target,OPAQUE,inner);if(walk(node.body,inner),isNode(node.else_))walk(node.else_,scope);return}case"Set":{let targets=node.targets.filter(isNode),value=OPAQUE;if(isNode(node.value))value=evalExpr(node.value,scope);else if(isNode(node.body))evalExpr(node.body,scope);for(let t of targets){let name=t.value;bind(scope,name,value.tag==="typed"&&targets.length===1?{...value,path:name}:OPAQUE)}return}case"Macro":bind(scope,String(node.name.value),OPAQUE),walkCallable(node,scope);return;case"Include":followTemplate("include",node.template,scope,(s,ref)=>({...pushFrame(s),seen:[...s.seen,ref]}),node.ignoreMissing===!0);return;case"Import":case"FromImport":{let withContext=node.withContext===!0;if(followTemplate("import",node.template,scope,(s,ref)=>({frames:[new Map],root:withContext?fields:[],seen:[...s.seen,ref]})),node.typename==="Import")bind(scope,String(node.target.value),OPAQUE);else for(let n of childNodes(node.names)){let local=n.typename==="Pair"?n.value:n;bind(scope,String(local.value),OPAQUE)}return}case"Extends":followTemplate("extends",node.template,scope,(s,ref)=>({frames:[new Map],root:fields,seen:[...s.seen,ref]}));return;case"Block":walk(node.body,scope);return;case"Switch":{evalExpr(node.expr,scope);for(let c of childNodes(node.cases))evalExpr(c.cond,scope),walk(c.body,scope);if(isNode(node.default))walk(node.default,scope);return}default:evalExpr(node,scope)}}let ast;try{ast=parseJinja(templateText)}catch(e){return[{code:ERR_TEMPLATE_SYNTAX,path:e.message}]}return walk(ast,{frames:[new Map],root:fields,seen:[]}),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}function isBooleanAccessor(stack,name){if(name.includes("."))return!1;if(!name.startsWith(HAS_PREFIX))return!1;for(let i=stack.length-1;i>=0;i--)for(let f of stack[i])if(name===hasAccessorName(f.name))return!0;return!1}function isPositionalAccessor(positional,name){return positional&&name===LAST_ACCESSOR}function find(fields,name){return fields.find((f)=>f.name===name)}function resolveTemplateVariable(stack,path){let segs=path.split("."),current;for(let i=stack.length-1;i>=0;i--){let hit=find(stack[i],segs[0]);if(hit){current=hit;break}}for(let i=1;current&&itok[0]===TOKEN_PARTIAL).map((tok)=>[tok[1],tok[2],tok[3]])}function hasDelimiterChange(tokens){return flatTokens(tokens).some((tok)=>tok[0]===TOKEN_DELIMITERS)}function delimiterConflict(tokens,inlinedAs){if(!hasDelimiterChange(tokens))return;return inlinedAs??partialTokens(tokens)[0]?.[0]}function commentSpans(tokens){return flatTokens(tokens).filter((tok)=>tok[0]===TOKEN_COMMENT).map((tok)=>[tok[2],tok[3]])}function withoutComments(text,tokens){let out="",pos=0;for(let[start,end]of commentSpans(tokens))out+=text.slice(pos,start),pos=end;return out+text.slice(pos)}function syntaxSection(e){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(e instanceof Error?e.message:"")?.[1]}function parseTemplate2(text){return parse3(text)}function verify(templateText,fields,opts){if(opts?.engine===TEMPLATE_ENGINE_JINJA)return verifyJinja(templateText,fields,opts);let errors=[],provider=opts?.provider,root=fields,referencedAtRoot=new Set,staticTexts=[templateText];function walk(tokens,stack,seen,positional=!1){let atRoot=stack.length===1&&stack[0]===root;for(let tok of tokens){let type=tok[0],value=tok[1];switch(type){case"name":case"&":case"{":{if(value===".")break;if(atRoot)referencedAtRoot.add(value.split(".")[0]);if(!resolve(stack,value)&&!isBooleanAccessor(stack,value)&&!isPositionalAccessor(positional,value))errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}case"#":case"^":{let sub=Array.isArray(tok[4])?tok[4]:[];if(value==="."){walk(sub,stack,seen,positional);break}if(atRoot)referencedAtRoot.add(value.split(".")[0]);let field=resolve(stack,value);if(!field){if(isPositionalAccessor(positional,value)){walk(sub,stack,seen,positional);break}if(isBooleanAccessor(stack,value)){walk(sub,stack,seen,positional);break}errors.push({code:ERR_VAR_NOT_ON_PAYLOAD,path:value});break}let push2=type==="#"&&field.fields!==void 0,iterates=type==="#"&&field.isArray===!0;walk(sub,push2?[...stack,field.fields]:stack,seen,iterates?field.fields!==void 0:positional);break}case">":{if(!provider)break;if(seen.includes(value)||seen.length>=MAX_DEPTH)break;let text=provider.resolve(value);if(text===void 0){errors.push({code:ERR_PARTIAL_UNRESOLVED,path:value});break}if(partialEngineMismatch(provider,value,TEMPLATE_ENGINE_MUSTACHE)){errors.push({code:ERR_TEMPLATE_ENGINE_UNSUPPORTED,path:value});break}let parsed=parseOrSyntaxError(text);if(!Array.isArray(parsed)){errors.push(parsed);break}let conflict2=delimiterConflict(parsed,value);if(conflict2!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict2});staticTexts.push(withoutComments(text,parsed)),walk(parsed,stack,[...seen,value],positional);break}default:break}}}let bodyTokens=parseOrSyntaxError(templateText);if(!Array.isArray(bodyTokens))return[bodyTokens];let conflict=delimiterConflict(bodyTokens,void 0);if(conflict!==void 0)errors.push({code:ERR_TEMPLATE_SYNTAX,path:conflict});return staticTexts[0]=withoutComments(templateText,bodyTokens),walk(bodyTokens,[root],[]),errors.push(...slotAndTagFindings(referencedAtRoot,staticTexts,opts)),errors}var TEMPLATE_REF_NODES=new Set(["Include","Import","FromImport","Extends"]);function literalTemplateRefs(node,out){if(TEMPLATE_REF_NODES.has(node.typename)){let t=node.template;if(t.typename==="Literal"&&typeof t.value==="string")out.push({ref:refOfTemplateName(t.value),optional:node.ignoreMissing===!0})}for(let child of childNodes(node))literalTemplateRefs(child,out)}function checkTemplateGraph(text,provider,path){let refs=[];literalTemplateRefs(parseJinja(text),refs);for(let{ref,optional}of refs){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let body=provider.resolve(ref);if(body===void 0){if(optional)continue;throw Error(`unresolved partial: ${ref}`)}if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_JINJA))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_JINJA));checkTemplateGraph(body,provider,[...path,ref])}}function renderJinja(body,ref,payload,provider,escaper){return checkTemplateGraph(body,provider,ref!==void 0?[ref]:[]),renderJinjaText(body,typeof payload==="object"&&payload!==null?payload:{},provider,escaper)}function expand(text,provider,path,inlinedAs){let tokens=parseTemplate2(text);if(delimiterConflict(tokens,inlinedAs)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let partials=partialTokens(tokens);if(partials.length===0)return text;let out="",pos=0;for(let[ref,start,end]of partials){if(path.includes(ref))throw Error(`partial cycle: ${[...path,ref].join(" -> ")}`);if(path.length>=MAX_DEPTH)throw Error(`partial depth exceeded ${MAX_DEPTH}: ${ref}`);let t=provider.resolve(ref);if(t===void 0)throw Error(`unresolved partial: ${ref}`);if(partialEngineMismatch(provider,ref,TEMPLATE_ENGINE_MUSTACHE))throw Error(partialEngineMessage(ref,TEMPLATE_ENGINE_MUSTACHE));out+=text.slice(pos,start)+expand(t,provider,[...path,ref],ref),pos=end}return out+text.slice(pos)}function render3(o){let body=o.template??(o.ref!==void 0?o.provider.resolve(o.ref):void 0);if(body===void 0)throw Error(`unresolved ref: ${o.ref??"(none)"}`);let engine=templateEngineOf(o.provider,o.template===void 0?o.ref:void 0,o.engine);if(o.verify!==void 0){let drift=verify(body,o.verify,{provider:o.provider,engine}).filter((e)=>e.code!==ERR_REQUIRED_SLOT_UNUSED);if(drift.length>0)throw Error(`render verify failed: ${drift.map((e)=>`${e.code} (${e.path})`).join(", ")}`)}let escaper=ESCAPERS[o.format??"text"],result=engine===TEMPLATE_ENGINE_JINJA?renderJinja(body,o.template===void 0?o.ref:void 0,o.payload,o.provider,escaper):renderMustache(body,o,escaper);if(o.maxChars!==void 0&&result.length>o.maxChars)throw Error(`render exceeded maxChars budget: ${result.length} > ${o.maxChars}`);return result}function failOnMissingVariable(){let proto=mustache_default.Writer.prototype,prev={escapedValue:proto.escapedValue,unescapedValue:proto.unescapedValue};for(let key of["escapedValue","unescapedValue"]){let original=prev[key];proto[key]=function(token,context,...rest){let name=String(token[1]);if(context.lookup(name)===void 0)throw Error(`render verify failed: ${ERR_VAR_NOT_ON_PAYLOAD} (${name})`);return original.call(this,token,context,...rest)}}return()=>{proto.escapedValue=prev.escapedValue,proto.unescapedValue=prev.unescapedValue}}function renderMustache(body,o,escaper){let expanded=expand(body,o.provider,o.ref!==void 0?[o.ref]:[]),prev=mustache_default.escape;mustache_default.escape=(v)=>escaper(typeof v==="string"?v:String(v));let result,restore=failOnMissingVariable();try{result=mustache_default.render(expanded,withDerivedAccessors(o.payload),{})}finally{mustache_default.escape=prev,restore()}return result}class InMemoryProvider{map;engine;constructor(map,options={}){this.map=map;this.engine=options.engine}resolve(ref){return Object.prototype.hasOwnProperty.call(this.map,ref)?this.map[ref]:void 0}engineOf(ref){return this.resolve(ref)===void 0?void 0:this.engine}}var TYPE_OBJECT="object",TYPE_FIELD="field";var TYPE_IDENTITY="identity",TYPE_RELATIONSHIP="relationship",TYPE_LAYOUT="layout",TYPE_SOURCE="source",TYPE_ORIGIN="origin",TYPE_TEMPLATE="template",TYPE_INDEX="index",TYPE_REQUIREMENT="requirement",TYPE_DIMENSION="dimension",TYPE_MEASURE="measure",TYPE_SEGMENT="segment";var DOC_ATTR_DESCRIPTION="description",DOC_ATTR_SUMMARY="summary";var FIELD_SUBTYPE_STRING="string";var FIELD_SUBTYPE_CURRENCY="currency",FIELD_SUBTYPE_ENUM="enum",FIELD_SUBTYPE_UUID="uuid",FIELD_SUBTYPE_URI="uri",FIELD_SUBTYPE_INET="inet",FIELD_SUBTYPE_DURATION="duration";var FIELD_ATTR_REQUIRED="required";var FIELD_ATTR_DEFAULT="default",FIELD_ATTR_MAX_LENGTH="maxLength";var FIELD_ATTR_FILTERABLE="filterable",FIELD_ATTR_SORTABLE="sortable";var FIELD_ATTR_OBJECT_REF="objectRef";var FIELD_ATTR_VALUES="values";var IDENTITY_ATTR_FIELDS="fields";var IDENTITY_REFERENCE_ATTR_REFERENCES="references";var OBJECT_SUBTYPE_ENTITY="entity",OBJECT_SUBTYPE_VALUE="value",OBJECT_SUBTYPE_PROJECTION="projection",OBJECT_SUBTYPE_REPORT="report";var OBJECT_REPORT_ATTR_FROM="from",OBJECT_REPORT_ATTR_DIMENSIONS="dimensions",OBJECT_REPORT_ATTR_MEASURES="measures",OBJECT_REPORT_ATTR_SEGMENT="segment",OBJECT_REPORT_ATTR_FILTER="filter",OBJECT_REPORT_ATTR_SPINE="spine";var FILTER_OP_EQ="eq",FILTER_OP_NE="ne",FILTER_OP_GT="gt",FILTER_OP_GTE="gte",FILTER_OP_LT="lt",FILTER_OP_LTE="lte",FILTER_OP_IN="in",FILTER_OP_LIKE="like",FILTER_OP_IS_NULL="isNull";var OPS_BY_SUBTYPE={string:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_ENUM]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],int:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],long:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],double:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],float:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],decimal:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_CURRENCY]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],boolean:[FILTER_OP_EQ,FILTER_OP_IS_NULL],date:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],time:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],timestamp:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_UUID]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_URI]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_LIKE,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_INET]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_IN,FILTER_OP_IS_NULL],[FIELD_SUBTYPE_DURATION]:[FILTER_OP_EQ,FILTER_OP_NE,FILTER_OP_GT,FILTER_OP_GTE,FILTER_OP_LT,FILTER_OP_LTE,FILTER_OP_IN,FILTER_OP_IS_NULL]};var RELATIONSHIP_SUBTYPE_ASSOCIATION="association",RELATIONSHIP_SUBTYPE_AGGREGATION="aggregation",RELATIONSHIP_SUBTYPE_COMPOSITION="composition";var RELATIONSHIP_ATTR_CARDINALITY="cardinality",RELATIONSHIP_ATTR_OBJECT_REF="objectRef",RELATIONSHIP_ATTR_THROUGH="through";var ON_DELETE_DEFAULT_BY_SUBTYPE={[RELATIONSHIP_SUBTYPE_COMPOSITION]:"cascade",[RELATIONSHIP_SUBTYPE_AGGREGATION]:"set-null",[RELATIONSHIP_SUBTYPE_ASSOCIATION]:"restrict"};var REQUIREMENT_SUBTYPE_FUNCTIONAL="functional",REQUIREMENT_SUBTYPE_ARCHITECTURAL="architectural";var REQUIREMENT_ATTR_DISPOSITION="disposition",REQUIREMENT_ATTR_TRACKED_BY="trackedBy",REQUIREMENT_ATTR_STATEMENT="statement",REQUIREMENT_ATTR_COUNTEREXAMPLE="counterexample";var REQUIREMENT_STATUS_PLANNED="planned",REQUIREMENT_STATUS_LIVE="live",REQUIREMENT_STATUS_PARTIAL="partial",REQUIREMENT_STATUS_RETIRED="retired",REQUIREMENT_STATUSES=["planned","live","partial","retired"];var REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK=["planned","partial"];var REQUIREMENT_LEVEL_SERVICE=3,REQUIREMENT_LEVEL_OBJECT=4;var ORIGIN_PASSTHROUGH_ATTR_FROM="from";var ORIGIN_AGGREGATE_ATTR_AGG="agg",ORIGIN_AGGREGATE_ATTR_OF="of",ORIGIN_AGGREGATE_ATTR_VIA="via",ORIGIN_AGGREGATE_ATTR_FILTER="filter";var ORIGIN_COMPUTED_ATTR_EXPR="expr";var AGGREGATE_FUNCTIONS=["count","sum","avg","min","max"];var AGG_ANY="any",AGG_ALL="all",AGG_COLLECT="collect",ORIGIN_AGG_VALUES=[...AGGREGATE_FUNCTIONS,AGG_ANY,AGG_ALL,AGG_COLLECT];var REPORTING_ATTR_OF="of",REPORTING_ATTR_VIA="via",REPORTING_ATTR_GRAINS="grains",REPORTING_ATTR_AGG="agg";var REPORTING_ATTR_FILTER="filter",REPORTING_ATTR_SEGMENT="segment",REPORTING_ATTR_NUMERATOR="numerator",REPORTING_ATTR_DENOMINATOR="denominator";var REPORTING_ATTR_DEFAULT="default";var FIELD_ATTR_COLUMN="column";var DB_COLUMN_TYPE_UUID="uuid",DB_COLUMN_TYPE_JSONB="jsonb";var DB_COLUMN_TYPE_TEXT="text",DB_COLUMN_TYPE_VARCHAR="varchar",DB_COLUMN_TYPE_CHARACTER_VARYING="character varying";var DB_COLUMN_TYPE_LEGAL_SUBTYPES={[DB_COLUMN_TYPE_UUID]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_JSONB]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_TEXT]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_VARCHAR]:[FIELD_SUBTYPE_STRING],[DB_COLUMN_TYPE_CHARACTER_VARYING]:[FIELD_SUBTYPE_STRING]};var SOURCE_ATTR_TABLE="table",SOURCE_ATTR_VIEW="view";var SOURCE_ATTR_KIND="kind";var SOURCE_KIND_VIEW="view";var LAYOUT_DATA_GRID_ATTR_PAGE_SIZE="pageSize",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD="defaultSortField",LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER="defaultSortOrder";var LAYOUT_DATA_GRID_ATTR_COLUMNS="columns";var TEMPLATE_SUBTYPE_PROMPT="prompt";var TEMPLATE_ATTR_PAYLOAD_REF="payloadRef",TEMPLATE_ATTR_TEXT_REF="textRef",TEMPLATE_ATTR_FORMAT="format";var TEMPLATE_ATTR_RESPONSE_REF="responseRef",TEMPLATE_ATTR_MAX_TOKENS="maxTokens";var TEMPLATE_ATTR_MODEL="model";var TEMPLATE_ATTR_PROMPT_STYLE="promptStyle";var TEMPLATE_ATTR_RESPONSE_FORMAT="responseFormat";var STATUSES=[REQUIREMENT_STATUS_LIVE,REQUIREMENT_STATUS_PARTIAL,REQUIREMENT_STATUS_PLANNED,REQUIREMENT_STATUS_RETIRED].filter((s)=>REQUIREMENT_STATUSES.includes(s)),STATUS_GLYPH={[REQUIREMENT_STATUS_LIVE]:"●",[REQUIREMENT_STATUS_PARTIAL]:"◐",[REQUIREMENT_STATUS_PLANNED]:"○",[REQUIREMENT_STATUS_RETIRED]:"⊘"},byCodeUnit=(a,b)=>ab?1:0;class ViewIndex{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(view){this.view=view;for(let n of view.nodes){let top=this.file(n,n.package,void 0);this.topOf.set(n.id,n);for(let g of n.memberGroups)for(let m of g.members)this.fileMember(m,n.package,top.id);if(n.type===TYPE_OBJECT)this.objects.push(top);else if(n.type===TYPE_TEMPLATE)this.templates.push(top);else if(n.type!==TYPE_REQUIREMENT)this.others.push(top)}for(let list of this.kids.values())list.sort((a,b)=>a.order-b.order||byCodeUnit(a.id,b.id));this.packages=view.packages.map((p)=>p.name);for(let r of view.requirements){let node=this.byId.get(r.id);if(node===void 0)continue;let parent=r.parent!==null?this.reqById.get(r.parent.id):void 0,entry={node,req:r,...parent!==void 0?{parent}:{},children:[],...r.level!==null?{level:r.level}:{},status:r.status,kind:r.subType};if(this.requirements.push(entry),this.reqById.set(r.id,entry),parent!==void 0)parent.children.push(entry);else this.topRequirements.push(entry)}}file(v,pkg,parent){let attrs={};for(let a of v.attrs)attrs[a.name]=a.value;let declaredOn="declaredOn"in v?v.declaredOn:null,n={id:v.id,type:v.type,subType:v.subType,name:v.name,package:pkg,order:v.order,...parent!==void 0?{parent}:{},path:v.path,anchor:"anchor"in v?v.anchor:"",...v.extends!==null&&!v.extends.unresolved?{extends:v.extends.id}:{},abstract:v.abstract,isArray:"isArray"in v?v.isArray:!1,...declaredOn!==null&&!declaredOn.unresolved?{inheritedFrom:declaredOn.id}:{},attrs,view:v};if(this.byId.set(n.id,n),parent!==void 0)this.kids.set(parent,[...this.kids.get(parent)??[],n]);return n}fileMember(m,pkg,parent){this.file(m,pkg,parent);for(let g of m.memberGroups)for(let c of g.members)this.fileMember(c,pkg,m.id)}children(id){return this.kids.get(id)??[]}ownerOf(id){let cur=this.byId.get(id);while(cur?.parent!==void 0)cur=this.byId.get(cur.parent);return cur?.id??id}top(id){return this.topOf.get(id)}fields(id){return this.children(id).filter((c)=>c.type===TYPE_FIELD)}source(id){return this.children(id).find((c)=>c.type===TYPE_SOURCE)}storage(id){let s=this.source(id);if(s===void 0)return;let view=s.attrs[SOURCE_ATTR_VIEW],table=s.attrs[SOURCE_ATTR_TABLE],isView=s.attrs[SOURCE_ATTR_KIND]===SOURCE_KIND_VIEW||typeof view==="string",name=typeof view==="string"?view:typeof table==="string"?table:void 0;return{kind:isView?"view":"table",...name!==void 0?{name}:{}}}isEntity(n){return n.type===TYPE_OBJECT&&n.subType===OBJECT_SUBTYPE_ENTITY}isPrompt(n){return n.type===TYPE_TEMPLATE&&n.subType===TEMPLATE_SUBTYPE_PROMPT}kindOf(n){if(n.type===TYPE_TEMPLATE)return n.subType===TEMPLATE_SUBTYPE_PROMPT?"prompt":"template";if(n.type!==TYPE_OBJECT)return"other";if(n.subType===OBJECT_SUBTYPE_ENTITY)return"entity";if(n.subType===OBJECT_SUBTYPE_VALUE)return"value";if(n.subType===OBJECT_SUBTYPE_PROJECTION)return"projection";if(n.subType===OBJECT_SUBTYPE_REPORT)return"report";return"object"}storedEntities(){return this.objects.filter((o)=>this.isEntity(o)&&!o.abstract)}claims(id){let v=this.byId.get(id)?.view;if(v===void 0)return[];return v.claims.flatMap((c)=>{let req=this.reqById.get(c.requirement.id);return req===void 0?[]:[{req,...c.member!==""?{member:c.member}:{}}]})}generated(id){return(this.topOf.get(id)?.files??[]).flatMap((g)=>g.paths.map((path)=>({path,generatedBy:g.generatedBy})))}routes(id){return this.topOf.get(id)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(r){let out=[],walk=(x)=>{out.push(x);for(let c of x.children)walk(c)};return walk(r),out}below(r){return this.subtree(r).slice(1)}rollup(r){let c={};for(let s of r.req.rollup)if(s.count>0)c[s.status]=s.count;return c}targetsOf(r){return r.req.targets.map((t)=>t.id)}linkTargets(r){return r.req.implementedBy.filter((l)=>l.resolves&&this.byId.has(l.target.id)).map((l)=>l.target.id)}featureOf(id){let count=new Map;for(let c of this.claims(id)){let top=c.req;while(top.parent!==void 0)top=top.parent;if(top.kind!==REQUIREMENT_SUBTYPE_FUNCTIONAL)continue;count.set(top,(count.get(top)??0)+1)}let best;for(let t of this.features()){let n=count.get(t)??0;if(n>0&&(best===void 0||n>(count.get(best)??0)))best=t}return best}features(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL)}qualities(){return this.topRequirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)}claimStatus(id){let cl=this.claims(id);if(cl.length===0)return"unclaimed";for(let s of STATUSES)if(cl.some((c)=>c.req.status===s))return s;return"unclaimed"}modelEdges(){let out=[],seen=new Set;for(let n of this.view.nodes){if(n.type===TYPE_REQUIREMENT)continue;for(let r of n.refs){let to=this.ownerOf(r.target.id),b=this.byId.get(to);if(to===n.id||b===void 0||b.type===TYPE_REQUIREMENT)continue;let key=`${r.attr}\x00${n.id}\x00${to}`;if(seen.has(key))continue;seen.add(key),out.push({kind:r.attr,from:n.id,to,...r.via!==null?{via:r.via.id}:{}})}}return out.sort((a,b)=>byCodeUnit(`${a.kind}\x00${a.from}\x00${a.to}`,`${b.kind}\x00${b.from}\x00${b.to}`))}slice(id){return this.view.slices.find((s)=>s.id===id)}}function esc(s){return String(s??"").replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function statusChip(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""} ${esc(status)}`}function statusGlyph(status){if(status==="")return"";return`${STATUS_GLYPH[status]??""}`}function levelBadge(r){return r.level!==void 0?`L${r.level}`:'—'}var GATE_SOURCE="gate";function verdictBadge(r){let gate=r.req.diagnostics.filter((d)=>d.source===GATE_SOURCE);if(gate.length===0)return"";let worst=gate.some((d)=>d.severity==="error")?"error":"warn",codes=gate.map((d)=>d.code).join(", "),n=gate.length;return`${worst==="error"?"✕":"!"} ${n} gate ${worst==="error"?n===1?"error":"errors":n===1?"warning":"warnings"}`}function dispositionPill(r){let d=r.node.attrs[REQUIREMENT_ATTR_DISPOSITION];return typeof d==="string"?`${esc(d)}`:""}function rollupBar(c){let total=STATUSES.reduce((a,s)=>a+(c[s]??0),0),title=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>`${c[s]} ${s}`).join(", ");if(total===0)return'
';let spans=STATUSES.filter((s)=>(c[s]??0)>0).map((s)=>``).join("");return``}function pct(x){return`${(Math.round(x*1e4)/100).toString()}%`}function legendHtml(withUnclaimed){return`
${STATUSES.map((s)=>statusChip(s)).join("")}${withUnclaimed?'unclaimed':""}! gate findingFill and glyph are the declared @status; outlines are meta verify findings; bars roll up what sits below. No colour here reports a test result.
`}function relHref(fromPage,toPage){let depth=fromPage.split("/").length-1;return"../".repeat(depth)+toPage}var PAGE_OVERVIEW="index.html",PAGE_MAP="map.html",PAGE_FEATURES="requirements/features.html",PAGE_QUALITIES="requirements/qualities.html",PAGE_MATRIX="matrix.html",PAGE_TRACE="trace.html",PAGE_PROMPTS="prompts.html",PAGE_API="api.html",PAGE_GAPS="gaps.html",PAGE_MODEL="model/index.html",ROWED_TYPES=new Set([TYPE_FIELD,TYPE_IDENTITY,TYPE_INDEX,TYPE_RELATIONSHIP,TYPE_DIMENSION,TYPE_MEASURE,TYPE_SEGMENT]),LEVEL_RULE_CODES=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),CODE_OBJECT_UNCLAIMED="WARN_REQUIREMENT_OBJECT_UNCLAIMED",byCodeUnit2=(a,b)=>ab?1:0,str=(v)=>typeof v==="string"?v:void 0,strs=(v)=>Array.isArray(v)?v.filter((x)=>typeof x==="string"):typeof v==="string"?[v]:[];function pkgDir(pkg){return pkg===""?"-root":pkg.split("::").join("/")}function localName(id){let i=id.lastIndexOf("::");return i<0?id:id.slice(i+2)}class Pages{ix;constructor(ix){this.ix=ix}objectPage(n){return n.path}packagePage(pkg){return`model/${pkgDir(pkg)}/index.html`}reqPage(r){return r.req.path}reqPath(r){return r.req.address}reqLabel(r){return r.req.label}pageOf(id){let path=this.ix.byId.get(id)?.path;return path===void 0||path===""?void 0:path}implLinks(r){return r.req.implementedBy.map((l)=>({ref:l.ref,resolves:l.resolves,...l.resolves&&this.ix.byId.has(l.target.id)?{target:l.target.id}:{}}))}attrValues(n,name){return n.view.attrs.find((a)=>a.name===name)?.values??[]}refLinks(n,name){return this.attrValues(n,name).flatMap((v)=>v.link!==null&&!v.link.unresolved?[v.link]:[])}refHtml(from,n,name,label){return this.attrValues(n,name).filter((v)=>v.link!==null).map((v)=>this.viewLink(from,v.link,label?.(v.text))).join(", ")}viewLink(from,l,label){return l.unresolved?`${esc(label??localName(l.label))} (unresolved)`:this.link(from,l.id,label)}memberAnchors(n,rowed){return this.ix.children(n.id).filter((c)=>!rowed.has(c.type)&&c.anchor!=="").map((c)=>``).join("")}kindClass(n){return`k-${this.ix.kindOf(n)}`}link(from,id,label){let page=this.pageOf(id),n=this.ix.byId.get(this.ix.ownerOf(id));if(page===void 0||n===void 0)return`${esc(label??localName(id))} (unresolved)`;let req=this.ix.reqById.get(id),text=label??(req!==void 0?this.reqLabel(req):id===n.id?n.name:`${n.name}.${id.slice(n.id.length+1)}`);return`${esc(text)}`}reqLink(from,r){return`${esc(this.reqLabel(r))}`}description(n){return esc(str(n.attrs[DOC_ATTR_DESCRIPTION])??str(n.attrs[DOC_ATTR_SUMMARY])??"")}topOf(r){let t=r;while(t.parent!==void 0)t=t.parent;return t}overview(title){let ix=this.ix,from=PAGE_OVERVIEW,stored=ix.storedEntities(),abstract=ix.objects.filter((o)=>ix.isEntity(o)&&o.abstract===!0).length,prompts=ix.templates.filter((t)=>ix.isPrompt(t)),values=ix.objects.filter((o)=>ix.kindOf(o)==="value").length,projections=ix.objects.filter((o)=>ix.kindOf(o)==="projection").length,reports=ix.objects.filter((o)=>ix.kindOf(o)==="report").length,vc=ix.view.counts,tiles=[];if(tiles.push({n:`${stored.length}`,l:`stored entities${abstract>0?` (${abstract} abstract base${abstract===1?"":"s"})`:""}`,href:relHref(from,PAGE_MAP)}),tiles.push({n:`${prompts.length}`,l:`declared prompt${prompts.length===1?"":"s"}, ${count(values,"payload or reply type","payload and reply types")}`,href:relHref(from,PAGE_PROMPTS)}),ix.hasRequirements())tiles.push({n:`${vc.requirements}`,l:`requirements: ${count(vc.functional,"feature")}, ${count(vc.architectural,"quality","qualities")}`,href:relHref(from,PAGE_FEATURES)});else tiles.push({n:`${projections+reports}`,l:`read models: ${projections} projection${projections===1?"":"s"}, ${reports} report${reports===1?"":"s"}`,href:relHref(from,PAGE_MODEL)});if(vc.coverageMeasured&&vc.entitiesTotal>0)tiles.push({n:`${vc.entitiesClaimed}/${vc.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:relHref(from,PAGE_GAPS)});else tiles.push({n:`${ix.packages.length}`,l:`package${ix.packages.length===1?"":"s"} in the model`,href:relHref(from,PAGE_MODEL)});if(ix.view.sources.routes){let routed=ix.objects.filter((o)=>ix.routes(o.id).length>0).length;tiles.push({n:`${routed}`,l:"objects with mounted REST routes",href:relHref(from,PAGE_API)})}else tiles.push({n:"—",l:"REST routes: none recorded by this run",href:relHref(from,PAGE_API)});tiles.push({n:ix.view.sources.files?`${vc.files}`:"—",l:ix.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:relHref(from,PAGE_TRACE)});let sources=["the effective model"];if(ix.view.sources.requirements)sources.push("the requirement gate's ledger");if(ix.view.sources.files)sources.push("the generation manifest");return{heading:esc(`What ${title} does`),sourcesLine:esc(joinAnd(sources)),tiles:tiles.map((t)=>({n:esc(t.n),l:esc(t.l),href:esc(t.href)})),hasRequirements:ix.hasRequirements(),featureCards:ix.features().map((r)=>this.capCard(from,r)),qualityCards:ix.qualities().map((r)=>this.capCard(from,r)),hasFeatures:ix.features().length>0,hasQualities:ix.qualities().length>0,packageCards:ix.packages.map((p)=>this.packageCard(from,p))}}capCard(from,r){let below=this.ix.below(r).length,claimed=this.ix.targetsOf(r).length;return{levelHtml:levelBadge(r),linkHtml:this.reqLink(from,r),statusHtml:statusChip(r.status),verdictHtml:verdictBadge(r),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),barHtml:rollupBar(this.ix.rollup(r)),countsLine:esc(`${below} requirement${below===1?"":"s"} below · ${claimed} model node${claimed===1?"":"s"} claimed`),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),glyphHtml:statusGlyph(c.status)})),hasChildren:r.children.length>0}}packageCard(from,pkg){let members=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((n)=>n.package===pkg),kinds=new Map;for(let m of members)kinds.set(this.ix.kindOf(m),(kinds.get(this.ix.kindOf(m))??0)+1);let kindLine=["entity","value","projection","report","prompt","template","object","other"].filter((k)=>kinds.has(k)).map((k)=>`● ${kinds.get(k)} ${plural(k,kinds.get(k)??0)}`).join(" · "),shown=members.slice(0,12);return{name:esc(pkg===""?"(no package)":pkg),href:esc(relHref(from,this.packagePage(pkg))),kindLineHtml:kindLine,membersHtml:shown.map((m)=>this.link(from,m.id)).join(", ")+(members.length>shown.length?` +${members.length-shown.length}`:"")}}map(){let ix=this.ix,groups=[],base=[{value:"",label:"Whole model"}];if(ix.templates.some((t)=>ix.isPrompt(t)))base.push({value:"@prompts",label:"Prompts and their payloads"});groups.push({label:"Model",options:base});for(let top of ix.topRequirements){let opts=[];for(let r of[top,...top.children]){let s=ix.slice(`requirement:${r.node.id}`);if(s===void 0)continue;let depth=r===top?"":" ";opts.push({value:s.id,label:`${depth}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)} (${ix.targetsOf(r).length})`})}if(opts.length>0)groups.push({label:`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLabel(top)}`,options:opts})}if(ix.packages.length>1)groups.push({label:"Package",options:ix.packages.map((p)=>({value:`package:${p}`,label:p===""?"(no package)":p}))});return{sliceGroups:groups.map((g)=>({label:esc(g.label),options:g.options.map((o)=>({value:esc(o.value),label:esc(o.label)}))})),hasRequirements:ix.hasRequirements()}}object(n){let ix=this.ix,from=this.objectPage(n),kind=ix.kindOf(n),claims=ix.claims(n.id),storage=ix.storage(n.id),storageLine=storage===void 0?kind==="value"?"value object: no storage":"no source":`${storage.kind}${storage.name!==void 0?` ${storage.name}`:""}`,fields=ix.fields(n.id).map((f)=>this.fieldRow(from,n,f)),hasColumn=fields.some((f)=>f.column!==""),keys=ix.children(n.id).filter((c)=>c.type===TYPE_IDENTITY||c.type===TYPE_INDEX||c.type===TYPE_RELATIONSHIP).map((c)=>this.keyRow(from,c)),reporting=ix.children(n.id).filter((c)=>c.type===TYPE_DIMENSION||c.type===TYPE_MEASURE||c.type===TYPE_SEGMENT).map((c)=>this.reportingRow(from,c)),layouts=ix.children(n.id).filter((c)=>c.type===TYPE_LAYOUT).map((l)=>this.layoutRow(l)),isUnclaimed=this.unclaimedEntity(n),whyRows=this.whyRows(from,n),referrers=ix.top(n.id)?.referencedBy??[],isPromptRef=(attr)=>attr===TEMPLATE_ATTR_PAYLOAD_REF||attr===TEMPLATE_ATTR_RESPONSE_REF,usedBy=[...new Set(referrers.filter((e)=>isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),refBy=[...new Set(referrers.filter((e)=>!isPromptRef(e.attr)).map((e)=>e.from.id))].sort(byCodeUnit2).map((id)=>this.link(from,id)),ext=n.extends!==void 0?this.link(from,n.extends):"";return{id:esc(n.id),name:esc(n.name),kindLabel:esc(`object.${n.subType}`),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › object.${esc(n.subType)}${this.memberAnchors(n,ROWED_TYPES)}`,isAbstract:n.abstract===!0,isUnclaimed,isReadOnly:storage?.kind==="view",kindBadge:esc(kind),description:this.description(n),storageLine:esc(storageLine),extendsHtml:ext,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),fields,hasFields:fields.length>0,hasColumn,showClaims:this.ix.hasRequirements(),keys,hasKeys:keys.length>0,reporting,hasReporting:reporting.length>0,layouts,hasLayouts:layouts.length>0,projection:kind==="projection"?this.projectionBlock(from,n):void 0,report:kind==="report"?this.reportBlock(from,n):void 0,routes:ix.routes(n.id).map((r)=>({method:esc(r.method),path:esc(r.path)})),hasRoutes:ix.routes(n.id).length>0,routesNote:!ix.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:usedBy.join(", "),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:claims.length}}unclaimedEntity(n){let ix=this.ix;if(!ix.isEntity(n)||n.abstract===!0)return!1;return ix.top(n.id)?.unclaimed===!0}whyRows(from,n){let claims=[...this.ix.claims(n.id)].sort((a,b)=>this.ix.requirements.indexOf(a.req)-this.ix.requirements.indexOf(b.req)),rows=[],lastTop;for(let c of claims){let top=this.topOf(c.req);rows.push({capabilityHtml:top===lastTop?"":this.reqLink(from,top),reqHtml:this.reqLink(from,c.req),statement:esc(str(c.req.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),levelHtml:levelBadge(c.req),statusHtml:statusChip(c.req.status),onHtml:c.member!==void 0?`${esc(c.member)}`:'whole object'}),lastTop=top}return rows}whyEmpty(n){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${esc(n.name)} exists.`;if(this.unclaimedEntity(n))return`No requirement claims ${esc(n.name)}. The gate reports this as ${CODE_OBJECT_UNCLAIMED}.`;return`No requirement claims ${esc(n.name)}.`}fieldRow(from,owner,f){let ref=this.refHtml(from,f,FIELD_ATTR_OBJECT_REF),values=f.subType===FIELD_SUBTYPE_ENUM?strs(f.attrs[FIELD_ATTR_VALUES]):[],flags=[];if(f.attrs[FIELD_ATTR_REQUIRED]===!0)flags.push("required");if(f.attrs[FIELD_ATTR_FILTERABLE]===!0)flags.push("filterable");if(f.attrs[FIELD_ATTR_SORTABLE]===!0)flags.push("sortable");if(f.attrs[FIELD_ATTR_MAX_LENGTH]!==void 0)flags.push(`max ${String(f.attrs[FIELD_ATTR_MAX_LENGTH])}`);if(f.attrs[FIELD_ATTR_DEFAULT]!==void 0)flags.push(`default ${fmt(f.attrs[FIELD_ATTR_DEFAULT])}`);if(this.ix.children(f.id).some((c)=>c.type===TYPE_ORIGIN))flags.push("derived");let claims=this.ix.claims(owner.id).filter((c)=>c.member!==void 0&&c.member.split(".")[0]===f.name);return{anchor:esc(f.anchor),name:esc(f.name),inheritedHtml:f.inheritedFrom!==void 0?`inherited`:"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:ref!==""?` → ${ref}`:"",valuesHtml:values.length>0?`
${values.map(esc).join(" | ")}
`:"",column:esc(str(f.attrs[FIELD_ATTR_COLUMN])??""),flagsHtml:flags.map((x)=>`${esc(x)}`).join(""),claimsHtml:claims.map((c)=>`${statusGlyph(c.req.status)} ${esc(this.reqLabel(c.req))}`).join("
")}}keyRow(from,c){let fields=strs(c.attrs[IDENTITY_ATTR_FIELDS]),target=this.refHtml(from,c,IDENTITY_REFERENCE_ATTR_REFERENCES)||this.refHtml(from,c,RELATIONSHIP_ATTR_OBJECT_REF),through=str(c.attrs[RELATIONSHIP_ATTR_THROUGH]),card=str(c.attrs[RELATIONSHIP_ATTR_CARDINALITY]),shape=c.type===TYPE_RELATIONSHIP?[card,through!==void 0?`through ${localName(through)}`:void 0].filter((x)=>x!==void 0).join(", "):`(${fields.join(", ")})`;return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),inheritedHtml:c.inheritedFrom!==void 0?'inherited':"",shape:esc(shape),targetHtml:target!==""?`→ ${target}`:""}}reportingRow(from,c){let a=c.attrs,parts=[],agg=str(a[REPORTING_ATTR_AGG]),of=this.refHtml(from,c,REPORTING_ATTR_OF,localName);if(agg!==void 0)parts.push(`${esc(agg)}(${of})`);else if(of!=="")parts.push(`of ${of}`);let num=str(a[REPORTING_ATTR_NUMERATOR]),den=str(a[REPORTING_ATTR_DENOMINATOR]);if(num!==void 0&&den!==void 0)parts.push(`${esc(num)} ÷ ${esc(den)}`);let via=str(a[REPORTING_ATTR_VIA]);if(via!==void 0)parts.push(`via ${esc(localName(via))}`);let grains=strs(a[REPORTING_ATTR_GRAINS]);if(grains.length>0)parts.push(`grains ${grains.map((g)=>`${esc(g)}`).join(" ")}`);let seg=str(a[REPORTING_ATTR_SEGMENT]);if(seg!==void 0)parts.push(`segment ${esc(seg)}`);if(a[REPORTING_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[REPORTING_ATTR_FILTER]))}`);if(a[REPORTING_ATTR_DEFAULT]!==void 0)parts.push(`default ${esc(fmt(a[REPORTING_ATTR_DEFAULT]))}`);return{anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),name:esc(c.name),definitionHtml:parts.join(" · ")}}layoutRow(l){let parts=[],cols=strs(l.attrs[LAYOUT_DATA_GRID_ATTR_COLUMNS]);if(cols.length>0)parts.push(`columns ${cols.map((c)=>`${esc(c)}`).join(", ")}`);let sort=str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD]);if(sort!==void 0)parts.push(`sorted by ${esc(sort)}${str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER])!==void 0?` ${esc(str(l.attrs[LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER]))}`:""}`);if(typeof l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]==="number")parts.push(`${l.attrs[LAYOUT_DATA_GRID_ATTR_PAGE_SIZE]} per page`);return{kind:esc(`${l.type}.${l.subType}`),name:esc(l.name),detailHtml:parts.join(", ")}}projectionBlock(from,n){let ix=this.ix,rows=[],bases=new Set;for(let f of ix.fields(n.id)){if(f.extends!==void 0)bases.add(ix.ownerOf(f.extends));for(let o of ix.children(f.id).filter((c)=>c.type===TYPE_ORIGIN)){let def=this.originDefinition(from,o);for(let src of this.refLinks(o,ORIGIN_PASSTHROUGH_ATTR_FROM))bases.add(ix.ownerOf(src.id));rows.push({field:esc(f.name),origin:esc(`origin.${o.subType}`),definitionHtml:def})}}return{basesHtml:[...bases].filter((b)=>b!==n.id).sort(byCodeUnit2).map((b)=>this.link(from,b)).join(", "),origins:rows,hasOrigins:rows.length>0}}originDefinition(from,o){let a=o.attrs,ref=(name)=>this.attrValues(o,name).map((v)=>v.link!==null&&!v.link.unresolved?this.link(from,v.link.id,localName(v.text)):`${esc(localName(v.text))}`).join(", "),parts=[],agg=str(a[ORIGIN_AGGREGATE_ATTR_AGG]);if(agg!==void 0)parts.push(`${esc(agg)}(${ref(ORIGIN_AGGREGATE_ATTR_OF)})`);else if(a[ORIGIN_AGGREGATE_ATTR_OF]!==void 0)parts.push(`of ${ref(ORIGIN_AGGREGATE_ATTR_OF)}`);if(a[ORIGIN_PASSTHROUGH_ATTR_FROM]!==void 0)parts.push(`from ${ref(ORIGIN_PASSTHROUGH_ATTR_FROM)}`);if(a[ORIGIN_AGGREGATE_ATTR_VIA]!==void 0)parts.push(`via ${esc(localName(String(a[ORIGIN_AGGREGATE_ATTR_VIA])))}`);if(a[ORIGIN_COMPUTED_ATTR_EXPR]!==void 0)parts.push(`${esc(fmt(a[ORIGIN_COMPUTED_ATTR_EXPR]))}`);if(a[ORIGIN_AGGREGATE_ATTR_FILTER]!==void 0)parts.push(`filter ${esc(fmt(a[ORIGIN_AGGREGATE_ATTR_FILTER]))}`);return parts.join(" · ")}reportBlock(from,n){let a=n.attrs,fromId=this.refLinks(n,OBJECT_REPORT_ATTR_FROM)[0]?.id??str(a[OBJECT_REPORT_ATTR_FROM]),resolve2=(name,kindType)=>{let hit=[fromId!==void 0?`${fromId}.${name}`:void 0,`${n.package===""?"":`${n.package}::`}${name}`].filter((x)=>x!==void 0).find((c)=>this.ix.byId.get(c)?.type===kindType||this.ix.byId.has(c)&&name.includes("."));return hit!==void 0?this.link(from,hit,name):`${esc(name)}`},spine=str(a[OBJECT_REPORT_ATTR_SPINE]);return{fromHtml:this.refHtml(from,n,OBJECT_REPORT_ATTR_FROM),spineHtml:spine!==void 0?`${esc(spine)}`:"",dimensionsHtml:strs(a[OBJECT_REPORT_ATTR_DIMENSIONS]).map((d)=>resolve2(d,TYPE_DIMENSION)).join(", "),measuresHtml:strs(a[OBJECT_REPORT_ATTR_MEASURES]).map((m)=>resolve2(m,TYPE_MEASURE)).join(", "),segmentHtml:strs(a[OBJECT_REPORT_ATTR_SEGMENT]).map((s)=>resolve2(s,TYPE_SEGMENT)).join(", "),filterHtml:a[OBJECT_REPORT_ATTR_FILTER]!==void 0?`${esc(fmt(a[OBJECT_REPORT_ATTR_FILTER]))}`:""}}generatedGroups(id){let groups=new Map;for(let f of this.ix.generated(id))groups.set(f.generatedBy,[...groups.get(f.generatedBy)??[],f.path]);return[...groups.keys()].sort(byCodeUnit2).map((g)=>({generator:esc(g),files:(groups.get(g)??[]).map((p)=>esc(p))}))}node(n){let ix=this.ix,from=this.objectPage(n),kindLabel=`${n.type}.${n.subType}`,whyRows=this.whyRows(from,n),attrs=this.attrRows(from,n),referrers=[...(ix.top(n.id)?.referencedBy??[]).map((e)=>e.from.id),...ix.claims(n.id).map((c)=>this.topOf(c.req).node.id)],refBy=[...new Set(referrers.filter((id)=>id!==n.id))].sort(byCodeUnit2).map((id)=>this.link(from,id));return{id:esc(n.id),name:esc(n.name),kindLabel:esc(kindLabel),crumbsHtml:`Model › ${esc(n.package===""?"(no package)":n.package)} › ${esc(kindLabel)}`,isAbstract:n.abstract===!0,description:this.description(n),extendsHtml:n.extends!==void 0?this.link(from,n.extends):"",attrs,hasAttrs:attrs.length>0,members:ix.children(n.id).map((c)=>({anchor:esc(c.anchor),kind:esc(`${c.type}.${c.subType}`),nameHtml:ix.reqById.has(c.id)?this.link(from,c.id):esc(c.name===""?`#${c.order}`:c.name),attrsHtml:this.attrRows(from,c).map((a)=>`@${a.name} ${a.valueHtml}`).join("
"),below:ix.children(c.id).length})),hasMembers:ix.children(n.id).length>0,whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:this.whyEmpty(n),referencedByHtml:refBy.join(", "),generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(from,n){return n.view.attrs.map((a)=>{let links=a.values.filter((v)=>v.link!==null&&!v.link.unresolved);return{name:esc(a.name),valueHtml:links.length>0&&links.length===a.values.length?links.map((v)=>this.link(from,v.link.id)).join(", "):`${esc(fmt(a.value))}`}})}prompt(n,text){let ix=this.ix,from=this.objectPage(n),payloadId=this.refLinks(n,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id,replyId=this.refLinks(n,TEMPLATE_ATTR_RESPONSE_REF)[0]?.id,vars=text!==void 0?templateVariables(text):void 0,payload=payloadId!==void 0?ix.byId.get(payloadId):void 0,reply=replyId!==void 0?ix.byId.get(replyId):void 0,payloadRows=payload!==void 0?ix.fields(payload.id).map((f)=>({name:esc(f.name),requiredHtml:f.attrs[FIELD_ATTR_REQUIRED]===!0?'required':"",type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),refHtml:this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)!==""?` → ${this.refHtml(from,f,FIELD_ATTR_OBJECT_REF)}`:"",usedHtml:vars===void 0?'text not read':vars.has(f.name)?"yes":'no'})):[],replyRows=reply!==void 0?ix.fields(reply.id).map((f)=>({name:esc(f.name),type:esc(`${f.subType}${f.isArray===!0?"[]":""}`),valuesHtml:f.subType===FIELD_SUBTYPE_ENUM?`
${strs(f.attrs[FIELD_ATTR_VALUES]).map(esc).join(" | ")}
`:""})):[],textRef=str(n.attrs[TEMPLATE_ATTR_TEXT_REF])??"",lines=text!==void 0?text.replace(/\n$/,"").split(` +`).length:0,attrs=[TEMPLATE_ATTR_FORMAT,TEMPLATE_ATTR_RESPONSE_FORMAT,TEMPLATE_ATTR_PROMPT_STYLE,TEMPLATE_ATTR_MODEL,TEMPLATE_ATTR_MAX_TOKENS].filter((k)=>n.attrs[k]!==void 0).map((k)=>`@${esc(k)} ${esc(fmt(n.attrs[k]))}`).join(""),claimed=ix.claims(n.id),whyRows=this.whyRows(from,n);return{name:esc(n.name),kindLabel:esc(`template.${n.subType}`),crumbsHtml:`Prompts › ${esc(n.package===""?"(no package)":n.package)} › template.${esc(n.subType)}${this.memberAnchors(n,new Set)}`,isUnclaimed:ix.hasClaims()&&claimed.length===0,description:this.description(n),attrsHtml:attrs,payloadHtml:payload!==void 0?this.link(from,payload.id):"none",payloadRows,hasPayload:payload!==void 0,replyHtml:reply!==void 0?this.link(from,reply.id):"none",replyRows,hasReply:reply!==void 0,textRef:esc(textRef),textMeta:esc(text!==void 0?`${textRef}.mustache · ${lines} line${lines===1?"":"s"}${str(n.attrs[TEMPLATE_ATTR_FORMAT])!==void 0?` · ${str(n.attrs[TEMPLATE_ATTR_FORMAT])}`:""}`:`${textRef}.mustache`),textHtml:text!==void 0?highlightVariables(text):"",hasText:text!==void 0,generated:this.generatedGroups(n.id),hasGenerated:ix.generated(n.id).length>0,generatedNote:!ix.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows,hasWhy:whyRows.length>0,whyEmptyHtml:ix.hasRequirements()?`No requirement claims ${esc(n.name)}. The gate counts entity coverage only, so this shows here and on the gaps page, not in meta verify.`:"This model declares no requirements."}}prompts(){let from=PAGE_PROMPTS,rows=this.ix.templates.map((p)=>{let payload=this.refHtml(from,p,TEMPLATE_ATTR_PAYLOAD_REF),reply=this.refHtml(from,p,TEMPLATE_ATTR_RESPONSE_REF),claims=this.ix.claims(p.id);return{linkHtml:this.link(from,p.id),kind:esc(`template.${p.subType}`),description:this.description(p),payloadHtml:payload!==""?payload:'none',replyHtml:reply!==""?reply:'none (outbound only)',claimsHtml:claims.length>0?claims.map((c)=>statusChip(c.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows,hasRows:rows.length>0}}requirements(kind,page){let tops=this.ix.topRequirements.filter((r)=>r.kind===kind),treeHtml=tops.length>0?`
    ${tops.map((r)=>this.treeNode(page,r)).join("")}
`:"";return{isFeatures:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL,featuresHref:esc(relHref(page,PAGE_FEATURES)),qualitiesHref:esc(relHref(page,PAGE_QUALITIES)),featureCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL).length,qualityCount:this.ix.requirements.filter((r)=>r.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL).length,treeHtml,hasTree:tops.length>0,emptyNote:kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(from,r){let links=this.implLinks(r).map((l)=>{if(l.target!==void 0)return`${this.link(from,l.target,l.ref)}`;return r.status===REQUIREMENT_STATUS_PLANNED?`${esc(l.ref)} (not yet)`:`${esc(l.ref)} (dangling)`}),bar=r.children.length>0?`${rollupBar(this.ix.rollup(r))}`:"";return`
  • ${`
    ${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}${dispositionPill(r)}${verdictBadge(r)}${bar}${links.join("")}
    ${esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??"")}
    `}${r.children.length>0?`
      ${r.children.map((c)=>this.treeNode(from,c)).join("")}
    `:""}
  • `}requirement(r){let ix=this.ix,from=this.reqPage(r),chain=[];for(let x=r;x!==void 0;x=x.parent)chain.unshift(x);let tab=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?{href:PAGE_FEATURES,label:"Features"}:{href:PAGE_QUALITIES,label:"Qualities"},inLedger=r.req.inLedger,diagnostics=r.req.diagnostics,links=this.implLinks(r),linkRows=links.map((l)=>{let target=l.target!==void 0?ix.byId.get(l.target):void 0;return{refHtml:target!==void 0?this.link(from,target.id,l.ref):`${esc(l.ref)}`,kind:esc(target!==void 0?`${target.type}.${target.subType}`:""),resolvesHtml:l.resolves?'resolves':r.status===REQUIREMENT_STATUS_PLANNED?'not yet (allowed on planned)':'dangling'}}),findings=diagnostics.filter((d)=>d.source===GATE_SOURCE),advisories=diagnostics.filter((d)=>d.source!==GATE_SOURCE),levelFinding=diagnostics.some((d)=>LEVEL_RULE_CODES.has(d.code)),testable=r.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL&&(r.level??0)>=REQUIREMENT_LEVEL_OBJECT,linksOk=links.length===0?"none":links.every((l)=>l.resolves)?"yes":"no",below=ix.below(r),slice=ix.slice(`requirement:${r.node.id}`),traceStart=r;while(traceStart!==void 0&&(traceStart.level??0)>REQUIREMENT_LEVEL_SERVICE)traceStart=traceStart.parent;let tracked=strs(r.node.attrs[REQUIREMENT_ATTR_TRACKED_BY]),desc=this.description(r.node);return{crumbsHtml:`${tab.label} › ${chain.map((x)=>x===r?esc(this.reqLabel(x)):this.reqLink(from,x)).join(" › ")}`,levelHtml:levelBadge(r),name:esc(this.reqLabel(r)),statusHtml:statusChip(r.status),dispositionHtml:dispositionPill(r),verdictHtml:verdictBadge(r),address:esc(`${r.req.qualifiedPath} · requirement.${r.kind}`),statement:esc(str(r.node.attrs[REQUIREMENT_ATTR_STATEMENT])??""),counterexample:esc(str(r.node.attrs[REQUIREMENT_ATTR_COUNTEREXAMPLE])??""),description:desc,hasDescription:desc!=="",linkRows,hasLinks:linkRows.length>0,linksEmpty:r.level!==void 0&&r.levelr.children.length,hasBelow:r.children.length>0,belowBarHtml:rollupBar(ix.rollup(r)),children:r.children.map((c)=>({levelHtml:levelBadge(c),linkHtml:this.reqLink(from,c),statusHtml:statusChip(c.status)})),sliceHref:slice!==void 0?esc(`${relHref(from,PAGE_MAP)}?slice=${encodeURIComponent(slice.id)}`):"",traceHref:traceStart!==void 0?esc(`${relHref(from,PAGE_TRACE)}?start=${encodeURIComponent(traceStart.node.id)}`):"",proof:[{what:"Loads",verdictHtml:'yes',how:"The loader enforces the closed @status enum and the required statement and counterexample."},{what:"Links resolve",verdictHtml:linksOk==="none"?'no links':linksOk==="yes"?'yes':'no',how:"ERR_REQUIREMENT_DANGLING_REF fails the build on live or partial; a planned entry may point ahead."},{what:"Level rules",verdictHtml:levelFinding?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:findings.length>0?`${findings.length}`:inLedger?'none':'not read',how:findings.length>0?findings.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:inLedger?`${advisories.length}`:'not read',how:advisories.length>0?advisories.map((d)=>`${esc(d.code)} ${esc(d.message)}`).join("
    "):inLedger?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:testable?'by generator':'not by default',how:testable?"The stock requirement-tests generator writes a test for this entry, and the codegen drift gate holds the test set to the ledger.":"The stock requirement-tests generator selects functional L4 and L5 entries only."},{what:"Test passes",verdictHtml:'not read',how:"verify never reads test results, so nothing here is coloured by one."},{what:"Status is true",verdictHtml:'unprovable',how:"No gate can prove the status. The colour is the author's claim, held to referential integrity."}].map((p)=>({what:esc(p.what),verdictHtml:p.verdictHtml,howHtml:p.how})),trackedHtml:tracked.map((t)=>`${esc(t)}`).join(" "),digest:esc(r.req.digest)}}matrix(){let ix=this.ix,from=PAGE_MATRIX,claimed=ix.requirements.flatMap((r)=>this.implLinks(r).flatMap((l)=>l.target!==void 0?[ix.ownerOf(l.target)]:[])),colSet=new Set([...ix.storedEntities(),...ix.templates.filter((t)=>ix.isPrompt(t))].map((n)=>n.id));for(let id of claimed)if(ix.byId.get(id)?.parent===void 0&&ix.byId.get(id)?.type!==TYPE_REQUIREMENT)colSet.add(id);let cols=[...colSet].map((id)=>ix.byId.get(id)).sort((a,b)=>ix.claims(b.id).length-ix.claims(a.id).length||byCodeUnit2(a.name,b.name)||byCodeUnit2(a.id,b.id)),head=`${cols.map((o)=>`
    ${this.link(from,o.id)}
    `).join("")}`,rows=[];for(let top of ix.topRequirements){let leaves=ix.subtree(top).filter((x)=>x.req.implementedBy.length>0);if(leaves.length===0)continue;rows.push(`${top.kind===REQUIREMENT_SUBTYPE_FUNCTIONAL?"Feature":"Quality"}: ${this.reqLink(from,top)}${cols.map(()=>'').join("")}`);for(let r of leaves){let tg=new Set(this.implLinks(r).filter((l)=>l.target!==void 0).map((l)=>ix.ownerOf(l.target))),label=this.reqPath(r).split(".").slice(1).join(".")||this.reqLabel(r);rows.push(`${levelBadge(r)}${esc(label)}${cols.map((o)=>tg.has(o.id)?`${statusGlyph(r.status)}`:'').join("")}`)}}return{tableHtml:rows.length>0?`${head}${rows.join("")}
    `:"",hasRows:rows.length>0,hasRequirements:ix.hasRequirements()}}trace(){let starts=this.ix.requirements.filter((r)=>r.level!==void 0&&r.level<=REQUIREMENT_LEVEL_SERVICE),fallback=starts.length===0?this.ix.topRequirements:[];return{options:[...starts,...fallback].map((r)=>({value:esc(r.node.id),label:esc(`${" ".repeat(Math.max(0,(r.level??1)-1))}${r.level!==void 0?`L${r.level} `:""}${this.reqLabel(r)}`)})),hasStarts:starts.length+fallback.length>0,hasUsage:!1}}gaps(){let ix=this.ix,from=PAGE_GAPS,cards=[],card=(title,count,source,why,bodyHtml)=>{cards.push({title:esc(title),count:esc(String(count)),source:esc(source),isGate:source==="meta verify",whyHtml:why,bodyHtml})};if(ix.view.sources.requirements){let findingsOf=(gate2)=>[...ix.requirements.flatMap((req)=>req.req.diagnostics.filter((d)=>d.source===GATE_SOURCE===gate2).map((d)=>({req,d}))),...ix.view.advisories.filter((d)=>d.path===""&&d.source===GATE_SOURCE===gate2).map((d)=>({d}))],table=(rows,chip)=>rows.length===0?'
    None.
    ':`${rows.map(({req,d})=>``).join("")}
    ${esc(d.code)}${req!==void 0?this.reqLink(from,req):""}
    ${esc(d.message)}
    `,gate=findingsOf(!0);card("Gate findings",gate.length,"meta verify","Printed by every run of the requirement gate.",table(gate,(sev)=>`chip v-${sev==="error"?"error":"warn"}`));let advisories=findingsOf(!1);card("Authoring advisories",advisories.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",table(advisories,()=>"chip"));let unclaimed=ix.storedEntities().filter((e)=>this.unclaimedEntity(e));card("Entities no requirement claims",unclaimed.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",unclaimed.length>0?unclaimed.map((e)=>this.link(from,e.id)).join(", "):'
    None.
    ');let outstanding=(r)=>REQUIREMENT_STATUSES_WITH_OUTSTANDING_WORK.includes(r.status),undecided=ix.requirements.filter((r)=>outstanding(r)&&r.node.attrs[REQUIREMENT_ATTR_DISPOSITION]===void 0&&!ix.below(r).some(outstanding));card("Undecided gaps",ix.view.counts.undecided,"meta verify","A partial or planned entry with no @disposition and no outstanding work below it: a gap nobody has ruled on. A roll-up parent is left out, since a ruling on it settles nothing. The gate counts these.",list(undecided.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)}`)))}if(ix.hasRequirements()){let behind=ix.requirements.filter((r)=>r.status===REQUIREMENT_STATUS_PLANNED&&ix.below(r).some((x)=>x.status===REQUIREMENT_STATUS_LIVE));card("Planned, with live work below",behind.length,"explorer check","L1 to L3 status is written by hand and never rolled up. Either the parent should say partial, or it is right and its children are ahead of it.",list(behind.map((r)=>`${levelBadge(r)}${this.reqLink(from,r)} ${statusChip(r.status)} ${rollupBar(ix.rollup(r))}`)));let prompts=ix.templates.filter((t)=>ix.isPrompt(t)&&ix.claims(t.id).length===0);card("Prompts no requirement claims",prompts.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",prompts.length>0?prompts.map((p)=>this.link(from,p.id)).join(", "):'
    None.
    ')}card("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let implied=ix.storedEntities().flatMap((e)=>{let declared=new Set(ix.children(e.id).filter((c)=>c.type===TYPE_IDENTITY&&c.attrs[IDENTITY_REFERENCE_ATTR_REFERENCES]!==void 0).flatMap((c)=>strs(c.attrs[IDENTITY_ATTR_FIELDS])));return ix.fields(e.id).filter((f)=>/[a-z]Id$/.test(f.name)&&!declared.has(f.name))});if(card("Fields that look like references but are not declared",implied.length,"explorer check","A field named like a foreign key with no identity.reference: the database does not enforce it and the map draws no line. Some are deliberate.",list(implied.map((f)=>`${this.link(from,f.id)} ${esc(f.subType)}`))),ix.templates.length>0){let unused=this.unusedPayload();card("Payload fields the prompt text never uses",unused===void 0?"—":unused.length,"explorer check","The template gate fails a variable the payload lacks; this is the other direction, payload bloat. Nested sections are not followed, so treat each as a lead.",unused===void 0?'
    No prompt text was read.
    ':list(unused.map(({p,f})=>`${this.link(from,p.id)}: ${this.link(from,f.id,f.name)}`)))}return{cards}}texts=new Map;unusedPayload(){let out=[],read=!1;for(let p of this.ix.templates){let text=this.texts.get(p.id),payload=this.refLinks(p,TEMPLATE_ATTR_PAYLOAD_REF)[0]?.id;if(text===void 0||payload===void 0)continue;read=!0;let vars=templateVariables(text);for(let f of this.ix.fields(payload))if(!vars.has(f.name))out.push({p,f})}return read?out:void 0}api(){let ix=this.ix,from=PAGE_API,groups=ix.objects.filter((o)=>ix.routes(o.id).length>0).map((o)=>({linkHtml:this.link(from,o.id),kind:esc(ix.kindOf(o)),isReadOnly:ix.storage(o.id)?.kind==="view",routes:ix.routes(o.id).map((r)=>({method:esc(r.method),methodClass:esc(r.method.toLowerCase()),path:esc(r.path)}))})),total=groups.reduce((a,g)=>a+g.routes.length,0);return{groups,hasGroups:groups.length>0,recorded:ix.view.sources.routes,summary:esc(`${total} route${total===1?"":"s"} on ${groups.length} object${groups.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((p)=>this.packageCard(PAGE_MODEL,p))}}packageIndex(pkg){let ix=this.ix,from=this.packagePage(pkg),rows=[...ix.objects,...ix.templates,...ix.others].filter((n)=>n.package===pkg).map((n)=>{let s=ix.storage(n.id),st=ix.claimStatus(n.id);return{linkHtml:this.link(from,n.id),kind:esc(`${n.type}.${n.subType}`),abstractHtml:n.abstract===!0?'abstract':"",storage:esc(s===void 0?"":`${s.kind}${s.name!==void 0?` ${s.name}`:""}`),fieldCount:ix.fields(n.id).length,statusHtml:st==="unclaimed"?this.unclaimedEntity(n)?'unclaimed':"":statusChip(st),description:this.description(n)}});return{name:esc(pkg===""?"(no package)":pkg),crumbsHtml:`Model › ${esc(pkg===""?"(no package)":pkg)}`,rows}}}function list(items){return items.length===0?'
    None.
    ':`
      ${items.map((i)=>`
    • ${i}
    • `).join("")}
    `}function fmt(v){return typeof v==="string"?v:JSON.stringify(v)}function joinAnd(xs){return xs.length<=1?xs[0]??"":`${xs.slice(0,-1).join(", ")} and ${xs[xs.length-1]}`}function count(n,one,many=`${one}s`){return`${n} ${n===1?one:many}`}function plural(kind,n){if(n===1)return kind;return kind==="entity"?"entities":`${kind}s`}var TAG=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function templateVariables(text){let out=new Set;for(let m of text.matchAll(TAG))if(m[1]!=="/")out.add(m[2].split(".")[0]);return out}function highlightVariables(text){let out="",last=0;for(let m of text.matchAll(/\{\{[^}]*\}?\}\}/g))out+=esc(text.slice(last,m.index)),out+=`${esc(m[0])}`,last=m.index+m[0].length;return out+esc(text.slice(last))}var NAV=[{key:"overview",label:"Overview",href:PAGE_OVERVIEW},{key:"map",label:"Model map",href:PAGE_MAP},{key:"requirements",label:"Requirements",href:PAGE_FEATURES},{key:"matrix",label:"Matrix",href:PAGE_MATRIX},{key:"trace",label:"Trace",href:PAGE_TRACE},{key:"prompts",label:"Prompts",href:PAGE_PROMPTS},{key:"api",label:"API",href:PAGE_API},{key:"gaps",label:"Gaps",href:PAGE_GAPS}];function textsMap(t){if(t===void 0)return new Map;if(t instanceof Map)return t;return new Map(Object.entries(t))}function createExplorer(opts){let ix=new ViewIndex(opts.view),pagesModel=new Pages(ix),texts=textsMap(opts.texts);for(let[id,text]of texts)pagesModel.texts.set(id,text);let tpl=(name)=>{let t=opts.templates[name];if(t===void 0)throw Error(`docs-site explorer: no template ${name}`);return t},provider=new InMemoryProvider({card:tpl("explorer-card.mustache")}),head=tpl("explorer-head.mustache"),foot=tpl("explorer-foot.mustache"),legend=legendHtml(ix.hasClaims()),pages=new Map,page=(template,href,nav,pageTitle,data,graph=!1)=>{if(pages.has(href))throw Error(`docs-site explorer: two pages map to ${href}`);let body=tpl(template);pages.set(href,()=>{let relRoot=relHref(href,""),payload={...data(),siteTitle:esc(opts.title),pageTitle:esc(pageTitle),stamp:esc(opts.stamp??""),relRoot,assetBase:opts.assetBase,cytoscapeSrc:opts.cytoscapeSrc(relRoot),graph3dSrc:opts.graph3dSrc(relRoot),needsGraph:graph,pageKey:nav,nav:NAV.map((n)=>({label:n.label,href:relHref(href,n.href),on:n.key===nav})),legendHtml:legend};return render3({template:head+body+foot,payload,provider,format:"text"})})};page("explorer-overview.html.mustache",PAGE_OVERVIEW,"overview","Overview",()=>pagesModel.overview(opts.title)),page("explorer-map.html.mustache",PAGE_MAP,"map","Model map",()=>pagesModel.map(),!0),page("explorer-requirements.html.mustache",PAGE_FEATURES,"requirements","Features",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_FUNCTIONAL,PAGE_FEATURES)),page("explorer-requirements.html.mustache",PAGE_QUALITIES,"requirements","Qualities",()=>pagesModel.requirements(REQUIREMENT_SUBTYPE_ARCHITECTURAL,PAGE_QUALITIES)),page("explorer-matrix.html.mustache",PAGE_MATRIX,"matrix","Matrix",()=>pagesModel.matrix()),page("explorer-trace.html.mustache",PAGE_TRACE,"trace","Trace",()=>pagesModel.trace(),!0),page("explorer-prompts.html.mustache",PAGE_PROMPTS,"prompts","Prompts",()=>pagesModel.prompts()),page("explorer-api.html.mustache",PAGE_API,"api","API",()=>pagesModel.api()),page("explorer-gaps.html.mustache",PAGE_GAPS,"gaps","Gaps",()=>pagesModel.gaps()),page("explorer-model.html.mustache",PAGE_MODEL,"map","Packages",()=>pagesModel.model());for(let pkg of ix.packages)page("explorer-package.html.mustache",pagesModel.packagePage(pkg),"map",pkg===""?"(no package)":pkg,()=>pagesModel.packageIndex(pkg));for(let n of ix.objects)page("explorer-object.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.object(n),!0);for(let t of ix.templates)page("explorer-prompt.html.mustache",pagesModel.objectPage(t),"prompts",t.name,()=>pagesModel.prompt(t,texts.get(t.id)));for(let n of ix.others)page("explorer-node.html.mustache",pagesModel.objectPage(n),"map",n.name,()=>pagesModel.node(n));for(let r of ix.requirements)page("explorer-requirement.html.mustache",pagesModel.reqPage(r),"requirements",pagesModel.reqLabel(r),()=>pagesModel.requirement(r));return{pages,graphData:()=>graphData(ix,pagesModel)}}function graphData(ix,p){let features=ix.features(),top=[...ix.objects,...ix.templates],nodes=top.map((n)=>{let feature=ix.featureOf(n.id),claims=ix.claims(n.id);return{id:n.id,name:n.name,kind:ix.kindOf(n),pkg:n.package,href:p.objectPage(n),abstract:n.abstract===!0?1:0,fields:ix.fields(n.id).length,claims:claims.length,status:ix.claimStatus(n.id),feature:feature!==void 0?features.indexOf(feature):-1,quality:claims.length>0&&claims.every((c)=>c.req.kind===REQUIREMENT_SUBTYPE_ARCHITECTURAL)?1:0,unclaimed:p.unclaimedEntity(n)?1:0,api:ix.routes(n.id).map((r)=>`${r.method} ${r.path}`),gen:ix.generated(n.id).length,storage:ix.storage(n.id)?.kind??""}}),ids=new Set(top.map((n)=>n.id)),slices={};for(let s of ix.view.slices)slices[s.id]=[...new Set(s.nodes.map((x)=>ix.ownerOf(x)).filter((x)=>ids.has(x)))].sort();let reqs=ix.requirements.map((r)=>({id:r.node.id,label:p.reqLabel(r),path:p.reqPath(r),level:r.level??0,status:r.status,kind:r.kind,parent:r.parent?.node.id??"",href:p.reqPage(r),targets:ix.linkTargets(r).map((id)=>ix.ownerOf(id)),statement:r.req.statement,rollup:ix.rollup(r),claimed:ix.targetsOf(r).length})),generated={};for(let n of top){let by=new Map;for(let f of ix.generated(n.id))by.set(f.generatedBy,(by.get(f.generatedBy)??0)+1);if(by.size>0)generated[n.id]=[...by.entries()].sort((a,b)=>a[0]b[0]?1:0)}let search=[];for(let n of top){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()});for(let f of ix.fields(n.id)){if(f.inheritedFrom!==void 0)continue;search.push({t:`${n.name}.${f.name}`,s:`field.${f.subType}`,h:p.pageOf(f.id)??p.objectPage(n),k:`${n.name}.${f.name} ${f.id}`.toLowerCase()})}}for(let n of ix.others){let desc=typeof n.attrs[DOC_ATTR_DESCRIPTION]==="string"?n.attrs[DOC_ATTR_DESCRIPTION]:"";search.push({t:n.name,s:`${n.type}.${n.subType}${n.package!==""?` · ${n.package}`:""}`,h:p.objectPage(n),k:`${n.name} ${n.id} ${desc}`.toLowerCase()})}for(let r of ix.requirements)search.push({t:p.reqLabel(r),s:`${r.level!==void 0?`L${r.level}`:"—"} ${r.kind}${r.status!==""?` · ${r.status}`:""} · ${p.reqPath(r)}`,h:p.reqPage(r),k:`${p.reqPath(r)} ${r.node.id} ${p.reqLabel(r)} ${r.req.statement}`.toLowerCase()});return{nodes,edges:ix.modelEdges().filter((e)=>ids.has(e.from)&&ids.has(e.to)).map((e)=>({s:e.from,t:e.to,k:e.kind,...e.via!==void 0?{v:localTail(e.via)}:{}})),slices,features:features.map((f)=>({id:f.node.id,label:p.reqLabel(f)})),reqs,generated,search,hasClaims:ix.hasClaims(),requirementType:TYPE_REQUIREMENT}}function localTail(id){let i=id.lastIndexOf(".");return i<0?id:id.slice(i+1)}function explorerFor(model){return createExplorer({view:model.view,title:model.title,templates:{...explorer_templates_default,...model.templates},texts:model.texts,...model.footer!==""&&{stamp:model.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor,templates:explorer_templates_default};if(typeof document<"u")startApp(window);function startApp(w){let site,loaded="",current={path:"",search:""},leave=[],parse4=(hash)=>{let raw2=hash.replace(/^#\/?/,""),u=new URL(raw2===""?"index.html":raw2,"http://explorer.invalid/"),path=u.pathname.slice(1);try{path=decodeURIComponent(path)}catch{}return{path:path===""?"index.html":path,search:u.search,anchor:u.hash.slice(1)}},route=(path,search,anchor="")=>`#/${path}${search}${anchor!==""?`#${anchor}`:""}`;w.MO_APP={href:(rel)=>{let r=parse4(rel);return route(r.path,r.search,r.anchor)},search:()=>current.search,replaceQuery:(search)=>{current={path:current.path,search:search==="?"?"":search},history.replaceState(null,"",route(current.path,current.search))},listen:(type,f)=>{document.addEventListener(type,f),leave.push(()=>document.removeEventListener(type,f))},onLeave:(f)=>{leave.push(f)}};let build=(model=w.MO_MODEL)=>{if(model===void 0)return!1;return site=explorerFor(model),w.MO_EXPLORER=site.graphData(),loaded=model.stamp,!0},sourceParam=new URLSearchParams(location.search).get("source"),source,live;if(sourceParam!==null&&sourceParam!=="")try{source=new URL(sourceParam,location.href)}catch{}let paintLive=()=>{if(sourceParam===null||sourceParam==="")return;let ok=live?.ok??!1,url=escapeHtml2(source?.href??sourceParam),html=ok?`● Following the running application at ${url}`:`● Cannot read ${url}${live!==void 0&&live.error!==""?` (${escapeHtml2(live.error)})`:""}${site!==void 0?", showing the model it last served":""}; trying again every second`,bar=document.getElementById("mo-live");if(bar===null)bar=document.createElement("div"),bar.id="mo-live",document.body.appendChild(bar);if(bar.innerHTML!==html)bar.innerHTML=html;let cls=ok?"live-source":"live-source down";if(bar.className!==cls)bar.className=cls;if(live!==void 0)bar.dataset.checked=new Date(live.at).toISOString();document.documentElement.setAttribute("data-mo-source",ok?"live":"down")},rewrite=(root,path,search)=>{for(let a of Array.from(root.querySelectorAll("a[href]"))){let raw2=a.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(raw2))continue;if(raw2.startsWith("#")){a.setAttribute("href",route(path,search,raw2.slice(1)));continue}let u=new URL(raw2,"http://explorer.invalid/"+path);a.setAttribute("href",route(u.pathname.slice(1),u.search,u.hash.slice(1)))}},show=(keepScroll)=>{let r=parse4(location.hash),draw=site?.pages.get(r.path);for(let f of leave)f();leave=[],current={path:r.path,search:r.search};let html=draw!==void 0?draw():`Not found

    No such page

    ${escapeHtml2(r.path)} is not a page of this model.

    Overview

    `,doc=new DOMParser().parseFromString(html,"text/html");doc.querySelectorAll("script").forEach((s)=>s.remove()),rewrite(doc,r.path,r.search);let y=window.scrollY;document.title=doc.title;for(let a of Array.from(document.body.attributes))document.body.removeAttribute(a.name);for(let a of Array.from(doc.body.attributes))document.body.setAttribute(a.name,a.value);if(document.body.replaceChildren(...Array.from(doc.body.childNodes).map((n)=>document.importNode(n,!0))),draw!==void 0)w.MO_THEME?.();if(keepScroll)window.scrollTo(0,y);else if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",r.path),paintLive()};window.addEventListener("hashchange",()=>{let r=parse4(location.hash);if(r.path===current.path&&r.search===current.search){if(r.anchor!=="")document.getElementById(r.anchor)?.scrollIntoView();return}show(!1)});let load=(file,done)=>{let s=document.createElement("script");s.src=`${file}?t=${Date.now()}`,s.onload=()=>{s.remove(),done()},s.onerror=()=>{s.remove(),done()},document.head.appendChild(s)},poll=()=>{load("explorer-stamp.js",()=>{if(w.MO_STAMP===void 0||w.MO_STAMP===loaded)return void setTimeout(poll,1000);let want=w.MO_STAMP;load("explorer-model.js",()=>{if(w.MO_MODEL?.stamp===want&&build())show(!0);setTimeout(poll,1000)})})},follow=(url)=>{let last="",tick=async()=>{try{let res=await fetch(url.href,{cache:"no-cache"});if(!res.ok)throw Error(`HTTP ${res.status}`);let text=await res.text();if(text!==last){let view=JSON.parse(text);if(typeof view!=="object"||view===null||!String(view.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let base=w.MO_MODEL,first=site===void 0;build({stamp:res.headers.get("etag")??`${text.length}`,title:base?.title??url.host,footer:base?.footer??"",texts:base?.texts??{},templates:base?.templates??{},view}),last=text,live={ok:!0,at:Date.now(),error:""},show(!first)}else live={ok:!0,at:Date.now(),error:""},paintLive()}catch(e){if(live={ok:!1,at:Date.now(),error:e instanceof Error?e.message:String(e)},site===void 0)document.body.innerHTML="

    No model yet

    The explorer is waiting for the running application's docs view.

    ";paintLive()}setTimeout(()=>void tick(),1000)};tick()},start=()=>{if(sourceParam!==null&&sourceParam!==""){if(source===void 0){live={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",paintLive();return}follow(source);return}if(!build())document.body.innerHTML="

    No model

    explorer-model.js did not load. Run meta gen to write it beside this page.

    ";else show(!1);setTimeout(poll,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",start);else start()}function escapeHtml2(s){return s.replace(/[&<>"']/g,(c)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}})(); diff --git a/server/rust/metaobjects-codegen/explorer-app/assets/explorer.css b/server/rust/metaobjects-codegen/explorer-app/assets/explorer.css new file mode 100644 index 0000000000..2be025a594 --- /dev/null +++ b/server/rust/metaobjects-codegen/explorer-app/assets/explorer.css @@ -0,0 +1,238 @@ +/* The model explorer's theme. `meta eject docs-site` copies this file to + codegen/docs-site/assets/, where an edit wins over the bundled copy. + + Colour rules (design report §4.2), which the classes below keep apart: + .s- a DECLARED status: filled chip, with its glyph in the text + .v- a GATE verdict: an outline (ring), never a fill + .bar .b-* a ROLL-UP of what sits below: a separate stacked bar + No class here colours a test result. */ + +:root { + --bg: #f7f7f5; --panel: #ffffff; --ink: #1d1f23; --muted: #5f6670; --line: #e2e3e0; + --accent: #3b5bdb; --accent-soft: #e8ecfd; --accent-ink: #ffffff; + --live: #2f9e44; --live-soft: #e3f5e7; --partial: #e8890c; --partial-soft: #fdf0dc; + --planned: #4c6ef5; --planned-soft: #e9edff; --retired: #868e96; --retired-soft: #eef0f2; + --bad: #e03131; --bad-soft: #fde8e8; --warn: #e8890c; --code: #f1f2ef; + --entity: #495057; --value: #7048e8; --prompt: #0c8599; --projection: #1971c2; --report: #c2255c; + --shadow: 0 1px 2px rgba(16, 24, 40, .04), 0 1px 3px rgba(16, 24, 40, .06); + --shadow-lift: 0 4px 14px rgba(16, 24, 40, .10); + color-scheme: light; +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #15171a; --panel: #1d2024; --ink: #e7e9ec; --muted: #9aa2ab; --line: #2e3238; + --accent: #8da2fb; --accent-soft: #252c47; --accent-ink: #15171a; + --live: #51cf66; --live-soft: #1e3324; --partial: #ffa94d; --partial-soft: #3a2c17; + --planned: #91a7ff; --planned-soft: #232a45; --retired: #adb5bd; --retired-soft: #2a2d31; + --bad: #ff6b6b; --bad-soft: #3a1f1f; --warn: #ffa94d; --code: #24272c; + --entity: #ced4da; --value: #b197fc; --prompt: #3bc9db; --projection: #74c0fc; --report: #f783ac; + --shadow: 0 1px 2px rgba(0, 0, 0, .3); --shadow-lift: 0 4px 14px rgba(0, 0, 0, .45); + color-scheme: dark; + } +} +:root[data-theme="dark"] { + --bg: #15171a; --panel: #1d2024; --ink: #e7e9ec; --muted: #9aa2ab; --line: #2e3238; + --accent: #8da2fb; --accent-soft: #252c47; --accent-ink: #15171a; + --live: #51cf66; --live-soft: #1e3324; --partial: #ffa94d; --partial-soft: #3a2c17; + --planned: #91a7ff; --planned-soft: #232a45; --retired: #adb5bd; --retired-soft: #2a2d31; + --bad: #ff6b6b; --bad-soft: #3a1f1f; --warn: #ffa94d; --code: #24272c; + --entity: #ced4da; --value: #b197fc; --prompt: #3bc9db; --projection: #74c0fc; --report: #f783ac; + --shadow: 0 1px 2px rgba(0, 0, 0, .3); --shadow-lift: 0 4px 14px rgba(0, 0, 0, .45); + color-scheme: dark; +} + +* { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; } +body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } +code, .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 12.5px; } +code { background: var(--code); border-radius: 4px; padding: 0 4px; } +code.digest { display: block; overflow-wrap: anywhere; font-size: 11.5px; padding: 4px 6px; } +pre code, .mono code { background: none; padding: 0; } + +/* ── Header ─────────────────────────────────────────────────────────────── */ +header.top { position: sticky; top: 0; z-index: 10; background: var(--panel); border-bottom: 1px solid var(--line); display: flex; gap: 16px; align-items: center; padding: 10px 20px; flex-wrap: wrap; } +.brand { font-weight: 700; letter-spacing: .2px; color: var(--ink); white-space: nowrap; } +.brand:hover { text-decoration: none; } +.brand small { font-weight: 400; color: var(--muted); margin-left: 6px; } +.nav { display: flex; gap: 4px; flex-wrap: wrap; } +.nav a { padding: 5px 10px; border-radius: 6px; color: var(--ink); white-space: nowrap; } +.nav a:hover { background: var(--code); text-decoration: none; } +.nav a.on { background: var(--accent-soft); color: var(--accent); font-weight: 600; } +#search { margin-left: auto; position: relative; } +#search input { width: 260px; max-width: 60vw; padding: 6px 10px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--ink); font: inherit; } +#search input:focus { outline: 2px solid var(--accent-soft); border-color: var(--accent); } +#results { position: absolute; right: 0; top: 36px; width: 420px; max-width: 90vw; max-height: 60vh; overflow: auto; background: var(--panel); border: 1px solid var(--line); border-radius: 8px; box-shadow: var(--shadow-lift); display: none; } +#results a { display: block; padding: 7px 12px; border-bottom: 1px solid var(--line); color: var(--ink); } +#results a:hover, #results a.sel { background: var(--accent-soft); text-decoration: none; } +#results a small { color: var(--muted); display: block; } +#results .none { padding: 8px 12px; color: var(--muted); } +#theme { padding: 5px 9px; } + +/* ── Page ───────────────────────────────────────────────────────────────── */ +main { padding: 24px 20px 20px; max-width: 1400px; margin: 0 auto; } +h1 { font-size: 22px; margin: 0 0 4px; line-height: 1.3; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +h2 { font-size: 16px; margin: 26px 0 10px; } +h3 { font-size: 14px; margin: 16px 0 6px; } +h3.first { margin-top: 0; } +.h-sub { color: var(--muted); font-weight: 400; } +.sub { color: var(--muted); } +.small { font-size: 12px; } +.crumbs { color: var(--muted); font-size: 12.5px; margin-bottom: 6px; } +.meta-line { margin-top: 4px; } +.page { margin-top: 14px; } +.card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; box-shadow: var(--shadow); min-width: 0; } +.grid { display: grid; gap: 12px; } +.tiles { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); margin: 18px 0; } +a.tile { color: var(--ink); transition: box-shadow .15s, border-color .15s, transform .15s; } +a.tile:hover { text-decoration: none; border-color: var(--accent); box-shadow: var(--shadow-lift); transform: translateY(-1px); } +.tile .n { font-size: 26px; font-weight: 700; letter-spacing: -.3px; font-variant-numeric: tabular-nums; } +.tile .l { color: var(--muted); font-size: 12.5px; line-height: 1.4; } +.two { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } +.side { grid-template-columns: minmax(0, 1fr) 340px; align-items: start; } +.apis { grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); } +@media (max-width: 1000px) { .side { grid-template-columns: minmax(0, 1fr); } } +@media (max-width: 900px) { .two { grid-template-columns: minmax(0, 1fr); } } + +table { border-collapse: collapse; width: 100%; } +th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; } +th { font-size: 12px; color: var(--muted); font-weight: 600; } +tr:target td { background: var(--accent-soft); } +table.kv th { width: 120px; } +.tablewrap { overflow-x: auto; } + +/* ── Status, verdict and roll-up ────────────────────────────────────────── */ +.chip { display: inline-flex; align-items: center; gap: 4px; padding: 1px 8px; border-radius: 999px; font-size: 12px; border: 1px solid var(--line); white-space: nowrap; margin: 1px 2px 1px 0; font-weight: 500; line-height: 1.6; } +h1 .chip { font-size: 12.5px; } +.s-live { background: var(--live-soft); color: var(--live); border-color: transparent; } +.s-partial { background: var(--partial-soft); color: var(--partial); border-color: transparent; } +.s-planned { background: var(--planned-soft); color: var(--planned); border-color: transparent; } +.s-retired { background: var(--retired-soft); color: var(--retired); border-color: transparent; text-decoration: line-through; } +.v-error, .v-unclaimed { background: transparent; color: var(--bad); border: 1.5px solid var(--bad); } +.v-warn { background: transparent; color: var(--warn); border: 1.5px solid var(--warn); } +.glyph { font-size: 12px; } +.g-live { color: var(--live); } .g-partial { color: var(--partial); } .g-planned { color: var(--planned); } .g-retired { color: var(--retired); } +.lvl { display: inline-block; min-width: 24px; text-align: center; font-size: 11px; font-weight: 700; border-radius: 4px; background: var(--code); color: var(--muted); padding: 0 4px; margin-right: 6px; line-height: 18px; } +h1 .lvl { font-size: 12px; line-height: 22px; } +.bar { display: flex; height: 8px; border-radius: 4px; overflow: hidden; background: var(--code); min-width: 80px; } +.bar span { display: block; height: 100%; } +.b-live { background: var(--live); } .b-partial { background: var(--partial); } .b-planned { background: var(--planned); } .b-retired { background: var(--retired); } +.minibar { display: inline-block; width: 90px; vertical-align: middle; margin: 0 4px; } +.legend { display: flex; gap: 8px; flex-wrap: wrap; font-size: 12px; color: var(--muted); align-items: center; margin: 4px 0; } +.legend-row { margin: 10px 0; } +.pill { font-size: 11px; color: var(--muted); border: 1px solid var(--line); border-radius: 4px; padding: 0 5px; margin-left: 4px; white-space: nowrap; } +.pill.gate { color: var(--accent); border-color: var(--accent); } +a.k-entity { color: var(--accent); font-weight: 500; } +span.k-entity { color: var(--entity); } .k-value { color: var(--value); } .k-prompt, .k-template { color: var(--prompt); } +.k-projection { color: var(--projection); } .k-report { color: var(--report); } +.kdot { font-size: 10px; } +.kdot.k-entity { color: var(--entity); } .kdot.k-value { color: var(--value); } .kdot.k-prompt { color: var(--prompt); } +.k-badge { color: var(--projection); } +.vals { color: var(--muted); font-size: 11.5px; } + +/* ── S1 cards ───────────────────────────────────────────────────────────── */ +.cap { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; } +.cap .card h3 { margin-top: 0; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.capcard .statement { margin: 2px 0 0; } +.rollup { margin: 10px 0 4px; } +.rollup .sub { margin-top: 3px; } +ul { padding-left: 18px; margin: 6px 0; } +.cap li, .kids li { margin: 4px 0; } +.members { margin-top: 8px; line-height: 1.9; } +details.summary { margin-top: 6px; } +details > summary { cursor: pointer; color: var(--muted); font-size: 12px; } +.note { border-left: 3px solid var(--accent); background: var(--accent-soft); padding: 8px 12px; border-radius: 6px; font-size: 13px; margin: 8px 0; } +.note.intro { margin: 4px 0 8px; font-size: 13.5px; } + +/* ── S5 tree ────────────────────────────────────────────────────────────── */ +.tabs { display: flex; gap: 6px; margin: 12px 0; flex-wrap: wrap; } +.tabs a { padding: 5px 12px; border: 1px solid var(--line); border-radius: 6px; color: var(--ink); background: var(--panel); } +.tabs a.on { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); } +.tree { margin-top: 10px; } +.tree ul { list-style: none; padding-left: 18px; border-left: 1px dashed var(--line); margin-left: 8px; } +.tree > ul { border-left: none; padding-left: 0; margin-left: 0; } +.tree li { margin: 4px 0; } +.tree .row { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; } +.tree .stmt { color: var(--muted); font-size: 12.5px; flex-basis: 100%; margin-left: 30px; } + +/* ── Graphs ─────────────────────────────────────────────────────────────── */ +.graph { width: 100%; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; } +#cy, #g3d { height: 640px; } #cymini { height: 260px; } #cytrace { height: 680px; } +#g3d { overflow: hidden; position: relative; } .graph[hidden] { display: none; } +.panel h3 { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.maplegend { margin-top: 8px; } +.toolbar { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; margin: 10px 0; } +select, button { padding: 5px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--panel); color: var(--ink); font: inherit; max-width: 100%; } +button { cursor: pointer; } +button:hover { border-color: var(--accent); } +.layout, .gen, .route { margin: 4px 0; } +.gen .pill { margin-left: 0; } + +/* ── S4 text ────────────────────────────────────────────────────────────── */ +pre { background: var(--code); padding: 10px 12px; border-radius: 8px; overflow: auto; font-size: 12px; white-space: pre-wrap; word-break: break-word; } +pre.text { max-height: 560px; } +.var { color: var(--prompt); } + +/* ── S6 proof ───────────────────────────────────────────────────────────── */ +.proof { font-size: 12.5px; } +.proof td:first-child { white-space: nowrap; font-weight: 500; } + +/* ── S7 matrix ──────────────────────────────────────────────────────────── */ +.mx { overflow: auto; max-height: 78vh; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); } +.mx table { width: auto; border-collapse: separate; border-spacing: 0; } +/* The header row is sticky as a whole: a sticky cell per column would paint over the slanted + label of the column before it. */ +.mx thead { position: sticky; top: 0; z-index: 2; background: var(--panel); } +.mx th.col { height: 150px; white-space: nowrap; vertical-align: bottom; padding: 0; } +.mx th.col.corner { position: sticky; left: 0; background: var(--panel); } +.mx th.col div { transform: rotate(-60deg); transform-origin: left bottom; width: 18px; margin-left: 12px; font-weight: 500; font-size: 11.5px; max-width: 18px; } +.mx th.col div a { display: inline-block; max-width: 150px; overflow: hidden; text-overflow: ellipsis; vertical-align: bottom; } +.mx th.col.unc div a { color: var(--bad); } +.mx td.c { width: 20px; min-width: 20px; height: 22px; padding: 0; text-align: center; font-size: 11px; border-right: 1px solid var(--line); } +.mx td.rh { position: sticky; left: 0; background: var(--panel); z-index: 1; border-right: 1px solid var(--line); white-space: nowrap; max-width: 360px; overflow: hidden; text-overflow: ellipsis; font-size: 12px; } +.mx tr.grp td { background: var(--code); font-weight: 600; } +.mx td.c.live { background: var(--live-soft); } .mx td.c.planned { background: var(--planned-soft); } +.mx td.c.partial { background: var(--partial-soft); } .mx td.c.retired { background: var(--retired-soft); } + +/* ── S9 gaps, API ───────────────────────────────────────────────────────── */ +.gap h3 { display: flex; gap: 8px; align-items: center; margin-top: 0; flex-wrap: wrap; } +.gap .why { margin-bottom: 8px; } +.count { font-weight: 700; font-size: 12px; border-radius: 999px; padding: 0 8px; background: var(--code); } +.method { display: inline-block; min-width: 52px; text-align: center; font: 600 11px ui-monospace, SFMono-Regular, Menlo, monospace; border-radius: 4px; padding: 1px 4px; background: var(--code); color: var(--muted); } +.m-GET, .m-get { background: var(--live-soft); color: var(--live); } +.m-POST, .m-post { background: var(--planned-soft); color: var(--planned); } +.m-PUT, .m-put, .m-PATCH, .m-patch { background: var(--partial-soft); color: var(--partial); } +.m-DELETE, .m-delete { background: var(--bad-soft); color: var(--bad); } + +footer { color: var(--muted); font-size: 12px; padding: 24px 20px; text-align: center; } + +/* ── Phone ──────────────────────────────────────────────────────────────── */ +@media (max-width: 700px) { + header.top { gap: 8px 12px; padding: 10px 16px; } + .nav { order: 3; flex-basis: 100%; flex-wrap: nowrap; overflow-x: auto; margin: 0 -16px; padding: 0 16px 2px; scrollbar-width: none; } + .nav::-webkit-scrollbar { display: none; } + #search { order: 4; margin-left: 0; flex-basis: 100%; } + #search input { width: 100%; max-width: none; } + #results { left: 0; right: 0; width: auto; max-width: none; } + #theme { margin-left: auto; } + main { padding: 16px; } + h1 { font-size: 20px; } + .tiles { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } + .tile .n { font-size: 22px; } + .cap { grid-template-columns: minmax(0, 1fr); } + .apis { grid-template-columns: minmax(0, 1fr); } + #cy, #g3d { height: 440px; } #cytrace { height: 520px; } + .mx { max-height: none; } + /* A wide table scrolls inside its own box, never the page. */ + main table { display: block; max-width: 100%; overflow-x: auto; } + .mx table { display: table; max-width: none; } + .tree .stmt { margin-left: 0; } + .tree ul { padding-left: 12px; margin-left: 4px; } +} +@media print { header.top, #search, #theme, .toolbar { display: none; } .card { box-shadow: none; } } + +/* ── The app following a running application (`index.html?source=`) ── */ +.live-source { position: fixed; right: 12px; bottom: 12px; z-index: 20; max-width: min(520px, calc(100vw - 24px)); background: var(--panel); border: 1px solid var(--line); border-radius: 8px; box-shadow: var(--shadow-lift); padding: 6px 10px; font-size: 12px; color: var(--muted); overflow-wrap: anywhere; } +.live-source b { color: var(--live); font-weight: 600; } +.live-source.down b { color: var(--bad); } diff --git a/server/rust/metaobjects-codegen/explorer-app/assets/explorer.js b/server/rust/metaobjects-codegen/explorer-app/assets/explorer.js new file mode 100644 index 0000000000..6cc6dff139 --- /dev/null +++ b/server/rust/metaobjects-codegen/explorer-app/assets/explorer.js @@ -0,0 +1,422 @@ +// The model explorer's scripts: search, the theme toggle, and the three graphs (the model map, +// an object page's one-hop mini-map, the trace). They read window.MO_EXPLORER, which the +// explorer app computes from the docs view (or, on a static export, assets/explorer-data.js +// sets); nothing here derives a model fact. +// `meta eject docs-site` copies this file to codegen/docs-site/assets/. +// +// On a static page this runs once, as it loads. In the explorer app (window.MO_APP is set) it +// runs again for every page the app draws, and the app supplies four things a page would +// otherwise take from its own URL: link targets, the query string, writing the query string +// back, and document listeners the app drops when the reader leaves the page. +(function () { + "use strict"; + function run() { + var APP = window.MO_APP || null; + var D = window.MO_EXPLORER || { nodes: [], edges: [], slices: {}, features: [], reqs: [], generated: {}, search: [] }; + var ROOT = document.body.getAttribute("data-root") || ""; + var query = function () { return APP ? APP.search() : location.search; }; + var setQuery = function (search) { if (APP) APP.replaceQuery(search); else history.replaceState(null, "", search ? location.pathname + search : location.pathname); }; + var listen = function (type, f) { if (APP) APP.listen(type, f); else document.addEventListener(type, f); }; + // A graph the app draws is destroyed when the reader leaves its page. + var graph = function (opts) { var c = cytoscape(opts); if (APP) APP.onLeave(function () { if (!c.destroyed()) c.destroy(); }); return c; }; + var $ = function (s, r) { return (r || document).querySelector(s); }; + var esc = function (s) { return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]; }); }; + var css = function (v) { return getComputedStyle(document.documentElement).getPropertyValue(v).trim(); }; + var STATUS = ["live", "partial", "planned", "retired"]; + var GLYPH = { live: "●", partial: "◐", planned: "○", retired: "⊘" }; + var PAL = ["#1971c2", "#e8590c", "#2b8a3e", "#ae3ec9", "#c2255c", "#0b7285", "#5c940d", "#f08c00"]; + var byId = {}; + D.nodes.forEach(function (n) { byId[n.id] = n; }); + var reqById = {}; + D.reqs.forEach(function (r) { reqById[r.id] = r; }); + var href = function (rel) { return APP ? APP.href(rel) : ROOT + rel; }; + var redraw = []; + + // ── Theme ─────────────────────────────────────────────────────────────── + var themeBtn = $("#theme"); + if (themeBtn) themeBtn.onclick = function () { + var cur = document.documentElement.getAttribute("data-theme"); + var dark = cur ? cur === "dark" : matchMedia("(prefers-color-scheme: dark)").matches; + var next = dark ? "light" : "dark"; + document.documentElement.setAttribute("data-theme", next); + try { localStorage.setItem("mo-theme", next); } catch (e) { /* private window: the toggle still works for this page */ } + redraw.forEach(function (f) { f(); }); + }; + + // ── Search ────────────────────────────────────────────────────────────── + // The built-in index ships in explorer-data.js and works from file://. When the site has been + // indexed with Pagefind (`npx pagefind --site `) and is served over http, Pagefind's + // full-text index answers instead. + var q = $("#q"), res = $("#results"), pagefind = null, pagefindTried = false, sel = -1; + function loadPagefind() { + // The app draws its own pages; a Pagefind index (of a static export) would link out of it. + if (APP || pagefindTried || !/^https?:$/.test(location.protocol)) return Promise.resolve(null); + pagefindTried = true; + // Pagefind takes its base URL from where pagefind.js loads, so loading it from ROOT makes every + // result URL carry the path the site is served under (a sub-path included). + var url = new URL(ROOT + "pagefind/pagefind.js", location.href).href; + return fetch(url, { method: "HEAD" }).then(function (r) { + if (!r.ok) return null; + return import(url).then(function (m) { pagefind = m; return m; }); + }).catch(function () { return null; }); + } + function show(items) { + sel = -1; + res.innerHTML = items.length ? items.map(function (x) { return '' + esc(x.t) + "" + esc(x.s) + ""; }).join("") : '
    No match
    '; + res.style.display = "block"; + } + function builtIn(v) { + var words = v.split(/\s+/).filter(Boolean); + return D.search.filter(function (x) { return words.every(function (w) { return x.k.indexOf(w) >= 0; }); }) + .sort(function (a, b) { return (a.t.toLowerCase().indexOf(words[0]) === 0 ? 0 : 1) - (b.t.toLowerCase().indexOf(words[0]) === 0 ? 0 : 1); }) + .slice(0, 25).map(function (x) { return { t: x.t, s: x.s, h: href(x.h) }; }); + } + if (q && res) { + q.addEventListener("input", function () { + var v = q.value.trim().toLowerCase(); + if (!v) { res.style.display = "none"; return; } + show(builtIn(v)); + loadPagefind().then(function (pf) { + if (!pf || q.value.trim().toLowerCase() !== v) return; + pf.search(v).then(function (r) { + return Promise.all(r.results.slice(0, 12).map(function (x) { return x.data(); })); + }).then(function (rows) { + if (q.value.trim().toLowerCase() !== v || !rows.length) return; + show(rows.map(function (d) { return { t: (d.meta && d.meta.title) || d.url, s: (d.excerpt || "").replace(/<[^>]+>/g, ""), h: d.url }; })); + }).catch(function () { /* keep the built-in results */ }); + }); + }); + q.addEventListener("keydown", function (e) { + var links = res.querySelectorAll("a"); + if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + sel = Math.max(0, Math.min(links.length - 1, sel + (e.key === "ArrowDown" ? 1 : -1))); + links.forEach(function (a, i) { a.classList.toggle("sel", i === sel); }); + } else if (e.key === "Enter" && links.length) { + location.href = links[Math.max(0, sel)].href; + } else if (e.key === "Escape") { res.style.display = "none"; q.blur(); } + }); + listen("click", function (e) { if (!$("#search").contains(e.target)) res.style.display = "none"; }); + listen("keydown", function (e) { + if (e.key === "/" && document.activeElement !== q && !/^(INPUT|SELECT|TEXTAREA)$/.test(document.activeElement.tagName)) { e.preventDefault(); q.focus(); } + }); + } + + if (typeof window.cytoscape !== "function") { + document.querySelectorAll(".graph").forEach(function (g) { + g.innerHTML = '
    The graph library did not load. Every node still has its own page.
    '; + }); + return; + } + + // ── Colours ───────────────────────────────────────────────────────────── + // Fill: the kind, the feature, or the DECLARED status of the claims on a node. + // Ring: a gate verdict (unclaimed). Never a test result. + function kindColour(n) { + return css({ entity: "--entity", value: "--value", prompt: "--prompt", template: "--prompt", projection: "--projection", report: "--report" }[n.kind] || "--entity"); + } + function fill(n, mode) { + if (n.abstract) return css("--retired"); + if (mode === "kind") return kindColour(n); + if (mode === "api") return n.api.length ? css("--accent") : css("--retired-soft"); + if (mode === "claims") return n.claims > 8 ? css("--live") : n.claims > 2 ? css("--partial") : n.claims > 0 ? css("--planned") : css("--retired-soft"); + if (mode === "cap") return n.feature >= 0 ? PAL[n.feature % PAL.length] : n.quality ? css("--retired") : css("--retired-soft"); + return n.status === "unclaimed" ? css("--retired-soft") : css("--" + n.status); + } + function legend(mode) { + var ring = D.hasClaims ? 'red ring: unclaimed (gate)' : ""; + if (mode === "cap") return '
    ' + D.features.map(function (f, i) { return '● ' + esc(f.label) + ""; }).join("") + '● qualities only○ no claim' + ring + "Fill is the feature (L1) with the most claims on the node; size is fields plus claims.
    "; + if (mode === "status") return '
    ' + STATUS.map(function (s) { return '' + GLYPH[s] + " " + s + ""; }).join("") + '○ no claim' + ring + "Fill is the best declared status among the requirements that claim the node.
    "; + if (mode === "api") return '
    ● mounted routes○ none
    '; + if (mode === "claims") return '
    ● more than 8 claims● 3 to 8● 1 or 2○ none' + ring + "
    "; + return '
    ' + ["entity", "value", "projection", "report", "prompt"].map(function (k) { return '● ' + k + ""; }).join("") + "Abstract bases are dashed and grey.
    "; + } + function shape(n) { return n.kind === "prompt" || n.kind === "template" ? "diamond" : n.kind === "value" ? "round-triangle" : n.kind === "projection" || n.kind === "report" ? "round-hexagon" : n.abstract ? "round-rectangle" : "ellipse"; } + function baseStyle() { + return [ + { selector: "node", style: { "background-color": "data(col)", label: "data(label)", width: "data(size)", height: "data(size)", shape: "data(shape)", color: css("--ink"), "font-size": 10, "text-valign": "bottom", "text-margin-y": 3, "border-width": 1, "border-color": css("--line"), "text-wrap": "none" } }, + { selector: "node[dashed = 1]", style: { "border-style": "dashed", "border-width": 2, "background-opacity": 0.4 } }, + { selector: "node[ring = 1]", style: { "border-width": 3, "border-color": css("--bad") } }, + { selector: "node[faded = 1]", style: { opacity: 0.18 } }, + { selector: "edge", style: { width: 1.2, "line-color": css("--muted"), "target-arrow-color": css("--muted"), "target-arrow-shape": "triangle", "curve-style": "bezier", "arrow-scale": 0.7, opacity: 0.6 } }, + { selector: "edge[ext = 1]", style: { "line-style": "dashed", "target-arrow-shape": "triangle-tee" } }, + { selector: "edge[faded = 1]", style: { opacity: 0.08 } }, + { selector: ":selected", style: { "border-width": 3, "border-color": css("--accent") } }, + ]; + } + var bar = function (c) { + var t = STATUS.reduce(function (a, s) { return a + (c[s] || 0); }, 0); + if (!t) return '
    '; + return '
    ' + STATUS.filter(function (s) { return c[s]; }).map(function (s) { return ''; }).join("") + "
    "; + }; + var chip = function (s) { return s ? '' + (GLYPH[s] || "") + " " + esc(s) + "" : ""; }; + var nodeLink = function (id) { var n = byId[id]; return n ? '' + esc(n.name) + "" : esc(id); }; + + // ── S2: the model map ─────────────────────────────────────────────────── + // cose from a grid (not from one point) gives the same picture on every load. + var COSE = { name: "cose", animate: false, randomize: false, nodeRepulsion: 12000, nodeOverlap: 24, idealEdgeLength: 90, componentSpacing: 90, gravity: 0.6, padding: 24, nodeDimensionsIncludeLabels: true }; + function seedGrid(els) { + var nodes = els.filter(function (e) { return !e.data.source; }), cols = Math.ceil(Math.sqrt(nodes.length || 1)); + nodes.forEach(function (e, i) { e.position = { x: (i % cols) * 120, y: Math.floor(i / cols) * 100 }; }); + } + var cyEl = $("#cy"); + if (cyEl) { + var cy = null; + var params = new URLSearchParams(query()); + var sliceSel = $("#slice"), colourSel = $("#colour"); + if (params.get("slice") && sliceSel.querySelector('option[value="' + CSS.escape(params.get("slice")) + '"]')) sliceSel.value = params.get("slice"); + if (params.get("colour") && colourSel.querySelector('option[value="' + CSS.escape(params.get("colour")) + '"]')) colourSel.value = params.get("colour"); + var focus = params.get("focus"); + // The 3D mode: the same nodes and edges as the flat map, drawn by 3d-force-graph, which the + // page loads only when a reader switches to it. An owned map template without the toggle + // simply has no 3D mode. + var dimSel = $("#dim"), g3dEl = $("#g3d"), g3d = null, g3dLast = null; + if (!dimSel || !g3dEl) dimSel = null; + else if (params.get("view") === "3d") dimSel.value = "3d"; + var drop3d = function () { + if (g3d) { g3d.pauseAnimation(); g3d._destructor(); g3d = null; } + if (g3dEl) g3dEl.innerHTML = ""; + }; + var fit3d = function () { if (g3d) g3d.width(g3dEl.clientWidth).height(g3dEl.clientHeight); }; + window.addEventListener("resize", fit3d); + if (APP) APP.onLeave(function () { window.removeEventListener("resize", fit3d); drop3d(); }); + var load3d = function (done) { + if (typeof window.ForceGraph3D === "function") return done(); + var s = document.createElement("script"); + s.src = g3dEl.getAttribute("data-src"); + s.onload = s.onerror = function () { s.remove(); done(); }; + document.head.appendChild(s); + }; + var draw3d = function (nodes, edges, inSlice, mode) { + drop3d(); + g3dEl.innerHTML = '
    Loading the 3D view…
    '; + load3d(function () { + // The reader may have left the page, or switched back, while the library loaded. + if (!g3dEl.isConnected || dimSel.value !== "3d") return; + if (typeof window.ForceGraph3D !== "function") { + g3dEl.innerHTML = '
    The 3D library did not load. The 2D map and every node page still work.
    '; + return; + } + g3dEl.innerHTML = ""; + var muted = css("--retired-soft"); + var data = { + nodes: nodes.map(function (n) { + return { id: n.id, name: n.name, pkg: n.pkg, col: inSlice && !inSlice[n.id] ? muted : fill(n, mode), val: 1 + Math.min(20, n.fields / 3 + n.claims / 2) }; + }), + links: edges.map(function (e) { return { source: e.s, target: e.t, label: e.v || e.k }; }), + }; + g3d = window.ForceGraph3D()(g3dEl) + .width(g3dEl.clientWidth).height(g3dEl.clientHeight) + .backgroundColor(css("--panel") || "#ffffff") + .nodeLabel(function (n) { return esc(n.name) + " · " + esc(n.pkg); }) + .nodeColor(function (n) { return n.col; }) + .nodeVal(function (n) { return n.val; }) + .nodeOpacity(0.95) + .linkLabel(function (l) { return esc(l.label); }) + .linkColor(function () { return css("--muted"); }) + .linkOpacity(0.45) + .linkDirectionalArrowLength(3).linkDirectionalArrowRelPos(1) + // One click shows the side panel, as a tap does on the flat map; a second click on + // the same node opens its page, as a double tap does. + .onNodeClick(function (n) { + var now = Date.now(); + if (g3dLast && g3dLast.id === n.id && now - g3dLast.t < 450) { + var node = byId[n.id]; + if (node) location.href = href(node.href); + g3dLast = null; + return; + } + g3dLast = { id: n.id, t: now }; + showPanel(n.id); + }) + .graphData(data); + // The drawn graph, for a script that drives the page (a test finds a node's position). + g3dEl.moGraph = g3d; + g3dEl.setAttribute("data-nodes", String(data.nodes.length)); + g3dEl.setAttribute("data-links", String(data.links.length)); + }); + }; + var promptSet = function () { + var s = {}; + D.nodes.forEach(function (n) { if (n.kind === "prompt" || n.kind === "template") s[n.id] = 1; }); + D.edges.forEach(function (e) { if (s[e.s] && (e.k === "payloadRef" || e.k === "responseRef")) s[e.t] = 1; }); + D.edges.forEach(function (e) { if (s[e.s] && byId[e.s] && byId[e.s].kind === "value" && e.k === "objectRef") s[e.t] = 1; }); + return s; + }; + var build = function (relayout) { + var slice = sliceSel.value, mode = colourSel.value, hide = $("#hideOut").checked, showExt = $("#showExt").checked; + $("#maplegend").innerHTML = legend(mode); + var inSlice = null; + if (slice === "@prompts") inSlice = promptSet(); + else if (slice && D.slices[slice]) { inSlice = {}; D.slices[slice].forEach(function (id) { inSlice[id] = 1; }); } + var showVals = $("#showValues").checked || slice === "@prompts" || (inSlice && Object.keys(inSlice).some(function (id) { return byId[id] && byId[id].kind !== "entity"; })); + var entityCount = D.nodes.filter(function (n) { return n.kind === "entity"; }).length; + if (!entityCount) showVals = true; + var nodes = D.nodes.filter(function (n) { return (n.kind === "entity" || showVals) && (!hide || !inSlice || inSlice[n.id]); }); + var ids = {}; + nodes.forEach(function (n) { ids[n.id] = 1; }); + var els = nodes.map(function (n) { + return { data: { id: n.id, label: n.name, col: fill(n, mode), size: 18 + Math.min(40, n.fields * 1.6 + n.claims * 2), shape: shape(n), faded: inSlice && !inSlice[n.id] ? 1 : 0, dashed: n.abstract, ring: n.unclaimed } }; + }); + D.edges.forEach(function (e, i) { + if (!ids[e.s] || !ids[e.t] || (!showExt && e.k === "extends")) return; + els.push({ data: { id: "e" + i, source: e.s, target: e.t, label: e.v || e.k, ext: e.k === "extends" ? 1 : 0, faded: inSlice && !(inSlice[e.s] && inSlice[e.t]) ? 1 : 0 } }); + }); + var three = dimSel !== null && dimSel.value === "3d"; + cyEl.hidden = three; + if (g3dEl) g3dEl.hidden = !three; + var qs3 = new URLSearchParams(query()); + if (three) qs3.set("view", "3d"); else qs3.delete("view"); + if (three) { + if (cy) { cy.destroy(); cy = null; } + draw3d(nodes, D.edges.filter(function (e) { return ids[e.s] && ids[e.t] && (showExt || e.k !== "extends"); }), inSlice, mode); + var sliceReq3 = slice.indexOf("requirement:") === 0 ? reqById[slice.slice("requirement:".length)] : null; + if (sliceReq3) $("#panel").innerHTML = slicePanel(sliceReq3, D.slices[slice] || []); + if (focus && byId[focus]) { showPanel(focus); focus = null; } + if (slice) qs3.set("slice", slice); else qs3.delete("slice"); + qs3.set("colour", mode); + setQuery("?" + qs3.toString()); + return; + } + drop3d(); + seedGrid(els); + var pan = cy && !relayout ? { pos: {} } : null; + if (pan) cy.nodes().forEach(function (n) { pan.pos[n.id()] = n.position(); }); + if (cy) cy.destroy(); + var keep = pan && els.every(function (el) { return el.data.source || pan.pos[el.data.id]; }); + cy = graph({ + container: cyEl, elements: els, wheelSensitivity: 0.3, maxZoom: 1.5, style: baseStyle(), + layout: keep ? { name: "preset", positions: function (n) { return pan.pos[n.id()]; }, fit: true, padding: 20 } : COSE, + }); + cy.on("tap", "node", function (ev) { showPanel(ev.target.id()); }); + cy.on("dbltap", "node", function (ev) { var n = byId[ev.target.id()]; if (n) location.href = href(n.href); }); + var sliceReq = slice.indexOf("requirement:") === 0 ? reqById[slice.slice("requirement:".length)] : null; + if (sliceReq) $("#panel").innerHTML = slicePanel(sliceReq, D.slices[slice] || []); + if (focus && byId[focus] && cy.getElementById(focus).length) { cy.getElementById(focus).select(); showPanel(focus); focus = null; } + var qs = qs3; + if (slice) qs.set("slice", slice); else qs.delete("slice"); + qs.set("colour", mode); + setQuery("?" + qs.toString()); + }; + ["#slice", "#colour", "#hideOut", "#showValues", "#showExt"].forEach(function (s) { $(s).onchange = function () { build(false); }; }); + if (dimSel) dimSel.onchange = function () { build(true); }; + $("#relayout").onclick = function () { + if (cy) cy.layout(Object.assign({}, COSE, { randomize: true })).run(); + if (g3d) g3d.d3ReheatSimulation(); + }; + redraw.push(function () { build(false); }); + build(true); + } + function slicePanel(r, nodes) { + return '
    Slice

    ' + (r.level ? "L" + r.level : "—") + '' + esc(r.label) + " " + chip(r.status) + "

    " + esc(r.statement) + "
    " + + "

    " + r.claimed + " model node" + (r.claimed === 1 ? "" : "s") + " claimed below

    " + nodes.map(nodeLink).join(", ") + + "

    Status below

    " + bar(r.rollup); + } + function showPanel(id) { + var n = byId[id], p = $("#panel"); + if (!n || !p) return; + var claims = D.reqs.filter(function (r) { return r.targets.indexOf(id) >= 0; }); + var byTop = {}; + claims.forEach(function (r) { var t = r; while (t.parent && reqById[t.parent]) t = reqById[t.parent]; (byTop[t.id] = byTop[t.id] || []).push(r); }); + var refs = D.edges.filter(function (e) { return e.s === id || e.t === id; }).length; + var gen = (D.generated[id] || []).map(function (g) { return '' + esc(g[0]) + " " + g[1]; }).join(" · "); + p.innerHTML = '
    ' + esc(n.pkg) + " · " + esc(n.kind) + (n.storage ? " · " + esc(n.storage) : "") + "
    " + + '

    ' + nodeLink(id) + (n.unclaimed ? ' unclaimed' : "") + "

    " + + "

    Why it exists (" + claims.length + " claim" + (claims.length === 1 ? "" : "s") + ")

    " + + (claims.length ? Object.keys(byTop).map(function (t) { + return "
    " + esc(reqById[t].label) + ": " + byTop[t].slice(0, 6).map(function (r) { return '' + (GLYPH[r.status] || "") + " " + esc(r.label) + ""; }).join(", ") + (byTop[t].length > 6 ? " +" + (byTop[t].length - 6) : "") + "
    "; + }).join("") : 'No requirement claims this node.') + + "

    Shape

    " + n.fields + " field" + (n.fields === 1 ? "" : "s") + ", " + refs + " reference" + (refs === 1 ? "" : "s") + + (n.api.length ? "

    API

    " + n.api.map(function (a) { return "
    " + esc(a) + "
    "; }).join("") : "") + + "

    Generated

    " + (gen || 'nothing traced'); + } + + // ── S3: the one-hop mini-map ──────────────────────────────────────────── + var mini = $("#cymini"); + if (mini) { + var me = mini.getAttribute("data-node"); + var drawMini = function () { + var es = D.edges.filter(function (e) { return e.s === me || e.t === me; }); + var ids = {}; + ids[me] = 1; + es.forEach(function (e) { ids[e.s] = 1; ids[e.t] = 1; }); + var els = Object.keys(ids).filter(function (id) { return byId[id]; }).sort().map(function (id) { + var n = byId[id]; + return { data: { id: id, label: n.name, col: fill(n, D.hasClaims ? "status" : "kind"), me: id === me ? 1 : 0, ring: n.unclaimed, shape: shape(n) } }; + }).concat(es.map(function (e, i) { return { data: { id: "m" + i, source: e.s, target: e.t, label: e.v || e.k } }; })); + mini.innerHTML = ""; + var c = graph({ + container: mini, elements: els, maxZoom: 1.3, + style: [ + { selector: "node", style: { "background-color": "data(col)", label: "data(label)", shape: "data(shape)", "font-size": 10, color: css("--ink"), "text-valign": "bottom", "text-margin-y": 2, width: 18, height: 18, "border-width": 1, "border-color": css("--line") } }, + { selector: "node[ring = 1]", style: { "border-width": 3, "border-color": css("--bad") } }, + { selector: "node[me = 1]", style: { width: 30, height: 30, "border-width": 3, "border-color": css("--accent") } }, + { selector: "edge", style: { width: 1, label: "data(label)", "font-size": 8, color: css("--muted"), "line-color": css("--muted"), "target-arrow-shape": "triangle", "target-arrow-color": css("--muted"), "curve-style": "bezier", "text-rotation": "autorotate", "text-background-color": css("--panel"), "text-background-opacity": 1, "text-background-padding": 2 } }, + ], + layout: { name: "concentric", concentric: function (n) { return n.data("me") ? 2 : 1; }, levelWidth: function () { return 1; }, startAngle: Math.PI, padding: 30, minNodeSpacing: 60 }, + }); + c.on("tap", "node", function (ev) { var n = byId[ev.target.id()]; if (n && n.id !== me) location.href = href(n.href); }); + }; + redraw.push(drawMini); + drawMini(); + } + + // ── S8: the trace ─────────────────────────────────────────────────────── + var tr = $("#cytrace"), tstart = $("#tstart"); + if (tr && tstart) { + var p2 = new URLSearchParams(query()).get("start"); + if (p2 && reqById[p2]) tstart.value = p2; + var drawTrace = function () { + var r0 = reqById[tstart.value]; + if (!r0) return; + var kids = {}; + D.reqs.forEach(function (r) { if (r.parent) (kids[r.parent] = kids[r.parent] || []).push(r); }); + var reqs = [], walk = function (r) { reqs.push(r); (kids[r.id] || []).forEach(walk); }; + walk(r0); + var cols = [[], [], [], []], els = [], seen = {}; + var add = function (id, label, col, data) { if (seen[id]) return; seen[id] = 1; cols[col].push(id); data.id = id; data.label = label; els.push({ data: data }); }; + reqs.forEach(function (r) { add("r:" + r.id, (r.level ? "L" + r.level + " " : "") + r.label, r.level >= 4 ? 1 : 0, { col: r.status ? css("--" + r.status) : css("--muted"), shape: "round-rectangle", go: r.href }); }); + reqs.forEach(function (r) { if (r.parent && seen["r:" + r.parent]) els.push({ data: { id: "pe:" + r.id, source: "r:" + r.parent, target: "r:" + r.id } }); }); + reqs.forEach(function (r) { + r.targets.forEach(function (t) { + var n = byId[t]; + if (!n) return; + add("o:" + t, n.name, 2, { col: kindColour(n), shape: shape(n), go: n.href, ring: n.unclaimed }); + if (!seen["le:" + r.id + ">" + t]) { seen["le:" + r.id + ">" + t] = 1; els.push({ data: { id: "le:" + r.id + ">" + t, source: "r:" + r.id, target: "o:" + t, col: r.status ? css("--" + r.status) : css("--muted") } }); } + }); + }); + cols[2].slice().forEach(function (oid) { + var id = oid.slice(2); + var gen = D.generated[id] || []; + if (!gen.length) return; + var total = gen.reduce(function (a, g) { return a + g[1]; }, 0); + var gid = "g:" + id; + add(gid, total + " generated (" + gen.map(function (g) { return g[0]; }).join(", ") + ")", 3, { col: css("--accent"), shape: "tag", go: byId[id].href }); + els.push({ data: { id: "ge:" + gid, source: oid, target: gid } }); + }); + var pos = {}; + cols.forEach(function (c, ci) { c.forEach(function (id, i) { pos[id] = { x: ci * 260, y: (i - c.length / 2) * 26 }; }); }); + tr.innerHTML = ""; + var c = graph({ + container: tr, elements: els, wheelSensitivity: 0.3, maxZoom: 1.6, + style: [ + { selector: "node", style: { "background-color": "data(col)", label: "data(label)", shape: "data(shape)", "font-size": 11, color: css("--ink"), "text-halign": "right", "text-valign": "center", "text-margin-x": 6, width: 12, height: 12 } }, + { selector: "node[ring = 1]", style: { "border-width": 2, "border-color": css("--bad") } }, + { selector: "edge", style: { width: 1, "line-color": "data(col)", opacity: 0.5, "curve-style": "unbundled-bezier" } }, + { selector: "edge[!col]", style: { "line-color": css("--muted") } }, + ], + layout: { name: "preset", positions: function (n) { return pos[n.id()]; }, fit: true, padding: 24 }, + }); + c.on("tap", "node", function (ev) { var go = ev.target.data("go"); if (go) location.href = href(go); }); + }; + tstart.onchange = function () { + var qs = new URLSearchParams(query()); qs.set("start", tstart.value); setQuery("?" + qs.toString()); + drawTrace(); + }; + redraw.push(drawTrace); + drawTrace(); + } + } + window.MO_THEME = run; + if (!window.MO_APP) run(); +})(); diff --git a/server/rust/metaobjects-codegen/explorer-app/index.html b/server/rust/metaobjects-codegen/explorer-app/index.html new file mode 100644 index 0000000000..6a91a98f6b --- /dev/null +++ b/server/rust/metaobjects-codegen/explorer-app/index.html @@ -0,0 +1,20 @@ + + + + + +Model explorer + + + + + +

    Loading the model…

    + + + + + + + + diff --git a/server/rust/metaobjects-codegen/src/client.rs b/server/rust/metaobjects-codegen/src/client.rs index 22dae76346..005a2b3ff3 100644 --- a/server/rust/metaobjects-codegen/src/client.rs +++ b/server/rust/metaobjects-codegen/src/client.rs @@ -206,10 +206,9 @@ fn client_crate( } lib_items.push((s.module(), exports)); let text = parts.entity_file(plan, s, route, &mut deps)?; - files.push(EmittedFile::new( - format!("{name}/src/{}.rs", s.module()), - text, - )); + files.push( + EmittedFile::new(format!("{name}/src/{}.rs", s.module()), text).from_node(&s.key), + ); } lib_items.sort(); files.push(EmittedFile::new( diff --git a/server/rust/metaobjects-codegen/src/commands.rs b/server/rust/metaobjects-codegen/src/commands.rs index a90b83e4aa..407bd6a962 100644 --- a/server/rust/metaobjects-codegen/src/commands.rs +++ b/server/rust/metaobjects-codegen/src/commands.rs @@ -184,10 +184,9 @@ fn command_crate( let route = s.route.as_ref().expect("a served entity has a route"); groups.push((s.module(), s.type_name.clone(), route.path.clone())); let text = parts.entity_file(s, route, cname, &client_crate)?; - files.push(EmittedFile::new( - format!("{name}/src/{}.rs", s.module()), - text, - )); + files.push( + EmittedFile::new(format!("{name}/src/{}.rs", s.module()), text).from_node(&s.key), + ); } groups.sort(); let manifest = parts.manifest(&name, c, &[cname, &client_crate]); diff --git a/server/rust/metaobjects-codegen/src/docs_site.rs b/server/rust/metaobjects-codegen/src/docs_site.rs new file mode 100644 index 0000000000..433bd945d7 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/docs_site.rs @@ -0,0 +1,458 @@ +//! `docs-site`: the model explorer, one browser app over the project's docs view, written with +//! no Node on the path (the Rust side of TypeScript's `docsSiteFile()`, `output: "app"`, and of +//! the JVM's `DocsSiteGenerator`; every port writes the same bytes). +//! +//! It builds the docs view from the model this run loaded ([`metaobjects::docs_view::build`]), +//! lists the files generated for each node (`generatedBy` and `sourceNode`, from +//! [`GenContext::generated_files`]: this run's, and the ones the hash manifest records outside +//! it), and writes, under `site/` (the `subDir` option; `""` writes at the output root): +//! +//! ```text +//! index.html, assets/explorer-app.js, the app: the same bytes in every port, from the +//! assets/cytoscape.min.js, repository's explorer-app/ (synced into this +//! assets/3d-force-graph.min.js crate by scripts/sync-explorer-app.sh) +//! assets/explorer.css, assets/explorer.js the theme, or the project's owned copy +//! explorer-model.js the docs view, the prompt texts, the title, the +//! footer and any owned templates, as one script +//! explorer-stamp.js the model's hash, which the open app polls +//! explorer.json the docs view itself, byte for byte +//! ``` +//! +//! The engine runs it after every other generator ([`Generator::reads_run_output`]), so a write +//! run and `verify` list the same files. Outside a run it lists what the hash manifest records. +//! +//! Options: `subDir` (default `site`); `title` (default: the project directory's name); `stamp` +//! (footer text, default none, so the site depends on the model alone); `prompts` (a directory, +//! relative to the project, holding prompt `.mustache` sources outside the metadata directories +//! and `templates/`); `verifyFile` (a `verify --format json` payload whose requirement rows the +//! explorer shows); `routesFile` (the routes the application mounts, `[{ node, method, path }]` +//! with `node` a resolution key). +//! +//! The site builder is engine, not an ejectable generator (the shared registry's `docs-site` +//! exemption): what an adopter changes is the theme. A project that owns it has its +//! `codegen/docs-site/assets/explorer.css`, `assets/explorer.js` and +//! `templates/explorer-*.mustache` used in place of the shipped ones. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use metaobjects::docs_view; +use serde_json::Value; + +use crate::generator::{EmittedFile, GenContext, GenError, Generator, Options, unknown_options}; +use crate::hashes::HashManifest; +use crate::sha256::sha256_hex; + +/// Bump when the emitted text changes shape, so a stored skip key never survives it. +const FORMAT: u32 = 1; +/// The failure of this generator. +const ERR_DOCS_SITE: &str = "ERR_DOCS_SITE"; + +const NAME: &str = "docs-site"; +const OPTION_SUB_DIR: &str = "subDir"; +const OPTION_TITLE: &str = "title"; +const OPTION_STAMP: &str = "stamp"; +const OPTION_PROMPTS: &str = "prompts"; +const OPTION_VERIFY_FILE: &str = "verifyFile"; +const OPTION_ROUTES_FILE: &str = "routesFile"; +const OPTIONS: &[&str] = &[ + OPTION_SUB_DIR, + OPTION_TITLE, + OPTION_STAMP, + OPTION_PROMPTS, + OPTION_VERIFY_FILE, + OPTION_ROUTES_FILE, +]; + +/// The default sub-directory of the output the site is written under. +pub const DEFAULT_SUB_DIR: &str = "site"; +/// Where an owned explorer theme lives, under the project (TypeScript's `OWNED_DOCS_SITE_DIR`). +pub const OWNED_DOCS_SITE_DIR: &str = "codegen/docs-site"; +/// The project's templates directory, searched for prompt sources. +const TEMPLATES_DIR: &str = "templates"; +/// The gen-state directory, under the project, whose manifest lists files outside a run. +const GEN_STATE_DIR: &str = ".metaobjects/.gen-state"; +/// The title when the project directory has no name. +const DEFAULT_TITLE: &str = "Metadata"; +/// The attribute naming a prompt's text. +const ATTR_TEXT_REF: &str = "textRef"; +const MUSTACHE: &str = ".mustache"; + +/// The data files the app reads, beside its shell. +pub const MODEL_FILE: &str = "explorer-model.js"; +pub const STAMP_FILE: &str = "explorer-stamp.js"; +pub const VIEW_FILE: &str = "explorer.json"; + +const ASSETS: &str = "assets/"; + +/// The app's files and this crate's copy of each (`explorer-app/`, synced from the repository +/// root's): every port ships the same bytes (TypeScript's `EXPLORER_APP_FILES`). +pub const APP_FILES: &[(&str, &str)] = &[ + ("index.html", include_str!("../explorer-app/index.html")), + ( + "assets/explorer-app.js", + include_str!("../explorer-app/assets/explorer-app.js"), + ), + ( + "assets/explorer.css", + include_str!("../explorer-app/assets/explorer.css"), + ), + ( + "assets/explorer.js", + include_str!("../explorer-app/assets/explorer.js"), + ), + ( + "assets/cytoscape.min.js", + include_str!("../explorer-app/assets/cytoscape.min.js"), + ), + ( + "assets/3d-force-graph.min.js", + include_str!("../explorer-app/assets/3d-force-graph.min.js"), + ), +]; + +/// The theme pair a project may own (`assets/` under the owned docs-site directory). +pub const THEME_ASSETS: &[&str] = &["explorer.css", "explorer.js"]; + +/// The templates an owned theme may replace; the app uses an owned one in place of its own. +pub const TEMPLATE_NAMES: &[&str] = &[ + "explorer-head.mustache", + "explorer-foot.mustache", + "explorer-card.mustache", + "explorer-overview.html.mustache", + "explorer-map.html.mustache", + "explorer-object.html.mustache", + "explorer-node.html.mustache", + "explorer-prompt.html.mustache", + "explorer-prompts.html.mustache", + "explorer-requirements.html.mustache", + "explorer-requirement.html.mustache", + "explorer-matrix.html.mustache", + "explorer-trace.html.mustache", + "explorer-gaps.html.mustache", + "explorer-api.html.mustache", + "explorer-model.html.mustache", + "explorer-package.html.mustache", +]; + +/// The docs-site generator, as shipped (no options). +#[derive(Debug, Clone, Copy, Default)] +pub struct DocsSiteGenerator; + +/// The generator as a project configured it. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct DocsSite { + pub sub_dir: Option, + pub title: Option, + pub stamp: Option, + pub prompts: Option, + pub verify_file: Option, + pub routes_file: Option, +} + +impl Generator for DocsSiteGenerator { + fn name(&self) -> &str { + NAME + } + + fn identity(&self) -> String { + DocsSite::default().identity() + } + + fn extra_inputs(&self) -> Vec { + DocsSite::default().extra_inputs() + } + + fn reads_run_output(&self) -> bool { + true + } + + fn configure(&self, options: &Options) -> Result, GenError> { + Ok(Box::new(DocsSite::from_options(options)?)) + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + DocsSite::default().generate(ctx) + } +} + +impl Generator for DocsSite { + fn name(&self) -> &str { + NAME + } + + fn identity(&self) -> String { + format!("{NAME}:{FORMAT}:{self:?}") + } + + /// The owned theme, the prompts directory and the verify and routes files are read beside + /// the model (ADR-0064): editing one regenerates. The hash manifest is not an input here: + /// the whole-run skip already re-runs when a recorded file changes or goes. + fn extra_inputs(&self) -> Vec { + let mut inputs = vec![OWNED_DOCS_SITE_DIR.to_string()]; + inputs.extend(self.prompts.clone()); + inputs.extend(self.verify_file.clone()); + inputs.extend(self.routes_file.clone()); + inputs + } + + fn reads_run_output(&self) -> bool { + true + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + let project = &ctx.collection.config_dir; + let verify = self + .verify_file + .as_deref() + .map(|f| read_json(&project.join(f))) + .transpose()?; + let routes = self + .routes_file + .as_deref() + .map(|f| read_json(&project.join(f))) + .transpose()?; + let recorded; + let files = match ctx.generated_files { + Some(f) => Some(f), + None => { + let m = HashManifest::load(&project.join(GEN_STATE_DIR)); + recorded = m.existed().then(|| m.entries().clone()); + recorded.as_ref() + } + }; + let manifest = files.map(|f| Value::Object(f.clone())); + let view = docs_view::build( + ctx.tree, + ctx.root, + verify.as_ref(), + manifest.as_ref(), + routes.as_ref(), + ); + let owned = project.join(OWNED_DOCS_SITE_DIR); + let title = self.title.clone().unwrap_or_else(|| { + project.file_name().map_or_else( + || DEFAULT_TITLE.to_string(), + |n| n.to_string_lossy().into_owned(), + ) + }); + let texts = read_prompt_texts(&view, &self.prompt_dirs(ctx)); + let site = emit(&SiteInput { + view: &view, + title: &title, + footer: self.stamp.as_deref().unwrap_or_default(), + texts: &texts, + assets_dir: Some(owned.join("assets")).filter(|d| d.is_dir()), + templates_dir: Some(owned.join(TEMPLATES_DIR)).filter(|d| d.is_dir()), + })?; + let prefix = match self.sub_dir.as_deref().unwrap_or(DEFAULT_SUB_DIR) { + "" => String::new(), + dir => format!("{dir}/"), + }; + Ok(site + .into_iter() + .map(|(path, text)| EmittedFile::new(format!("{prefix}{path}"), text)) + .collect()) + } +} + +impl DocsSite { + /// The generator from a project's options for it. + pub fn from_options(options: &Options) -> Result { + if options.keys().any(|k| !OPTIONS.contains(&k.as_str())) { + return Err(unknown_options(NAME, options, OPTIONS)); + } + let text = |key: &str| -> Result, GenError> { + match options.get(key) { + None => Ok(None), + Some(Value::String(s)) => Ok(Some(s.clone())), + Some(other) => Err(GenError::new( + ERR_DOCS_SITE, + format!("the generator {NAME} takes \"{key}\" as a string, got {other}"), + )), + } + }; + Ok(Self { + sub_dir: text(OPTION_SUB_DIR)?.map(|s| s.trim_end_matches('/').to_string()), + title: text(OPTION_TITLE)?, + stamp: text(OPTION_STAMP)?, + prompts: text(OPTION_PROMPTS)?, + verify_file: text(OPTION_VERIFY_FILE)?, + routes_file: text(OPTION_ROUTES_FILE)?, + }) + } + + /// Where prompt `.mustache` sources are looked for: the directories the model was loaded + /// from, the project's `templates/` and the `prompts` directory, each once. + fn prompt_dirs(&self, ctx: &GenContext<'_>) -> Vec { + let project = &ctx.collection.config_dir; + let mut dirs: Vec = Vec::new(); + let mut add = |d: PathBuf| { + if d.is_dir() && !dirs.contains(&d) { + dirs.push(d); + } + }; + for root in &ctx.collection.source_roots { + add(if root.is_dir() { + root.clone() + } else { + root.parent().map(Path::to_path_buf).unwrap_or_default() + }); + } + add(project.join(TEMPLATES_DIR)); + if let Some(p) = &self.prompts { + add(project.join(p)); + } + dirs + } +} + +fn read_json(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|e| { + GenError::new( + ERR_DOCS_SITE, + format!("{NAME}: could not read {}: {e}", path.display()), + ) + })?; + serde_json::from_str(&text).map_err(|e| { + GenError::new( + ERR_DOCS_SITE, + format!("{NAME}: {} is not JSON: {e}", path.display()), + ) + }) +} + +/// What the site is built from. +pub struct SiteInput<'a> { + /// The docs view ([`docs_view::build`]). + pub view: &'a Value, + /// The project's name, as the header and the home page print it. + pub title: &'a str, + /// Printed in every footer; `""` for none. + pub footer: &'a str, + /// Prompt text by template node id. + pub texts: &'a BTreeMap, + /// An owned theme directory (holding `explorer.css`, `explorer.js`). + pub assets_dir: Option, + /// An owned templates directory. + pub templates_dir: Option, +} + +/// Every file of the site, site-relative, in write order. +pub fn emit(input: &SiteInput<'_>) -> Result, GenError> { + let mut files: Vec<(String, String)> = Vec::new(); + for (path, text) in APP_FILES { + let theme = path + .strip_prefix(ASSETS) + .is_some_and(|a| THEME_ASSETS.contains(&a)); + if !theme { + files.push(((*path).to_string(), (*text).to_string())); + } + } + for asset in THEME_ASSETS { + let path = format!("{ASSETS}{asset}"); + let text = match read_if_present(input.assets_dir.as_deref(), asset)? { + Some(owned) => owned, + None => app_file(&path).to_string(), + }; + files.push((path, text)); + } + let mut templates = BTreeMap::new(); + for name in TEMPLATE_NAMES { + if let Some(owned) = read_if_present(input.templates_dir.as_deref(), name)? { + templates.insert((*name).to_string(), owned); + } + } + let (script, stamp) = model_script( + input.title, + input.footer, + input.texts, + &templates, + input.view, + ); + files.push((MODEL_FILE.to_string(), script)); + files.push((STAMP_FILE.to_string(), docs_view::stamp_script(&stamp))); + files.push((VIEW_FILE.to_string(), docs_view::serialize(input.view))); + Ok(files) +} + +/// This crate's copy of an app file. +fn app_file(path: &str) -> &'static str { + APP_FILES + .iter() + .find(|(p, _)| *p == path) + .map(|(_, t)| *t) + .unwrap_or_default() +} + +fn read_if_present(dir: Option<&Path>, name: &str) -> Result, GenError> { + let Some(p) = dir.map(|d| d.join(name)).filter(|p| p.is_file()) else { + return Ok(None); + }; + std::fs::read_to_string(&p).map(Some).map_err(|e| { + GenError::new( + ERR_DOCS_SITE, + format!("{NAME}: could not read {}: {e}", p.display()), + ) + }) +} + +/// The app's data script and the stamp it carries: the first 16 hex digits of the SHA-256 of +/// the payload ([`docs_view::model_payload`]). The same bytes as TypeScript's +/// `explorerModelScript`. +pub fn model_script( + title: &str, + footer: &str, + texts: &BTreeMap, + templates: &BTreeMap, + view: &Value, +) -> (String, String) { + let payload = docs_view::model_payload(title, footer, texts, templates, view); + let stamp = sha256_hex(payload.as_bytes())[..16].to_string(); + (docs_view::model_script(&stamp, &payload), stamp) +} + +/// Each prompt's `.mustache` text from the directories its `@textRef` resolves in, by template +/// node id. A ref that is absolute or climbs out with `..` is not read, so a model cannot pull +/// an arbitrary file into a published page. +pub fn read_prompt_texts(view: &Value, dirs: &[PathBuf]) -> BTreeMap { + let mut out = BTreeMap::new(); + for n in view["nodes"].as_array().into_iter().flatten() { + let mut text_ref = None; + for a in n["attrs"].as_array().into_iter().flatten() { + if a["name"] == ATTR_TEXT_REF + && let Some(v) = a["value"].as_str() + { + text_ref = Some(v); + } + } + let Some(r) = text_ref else { + continue; + }; + let segments: Vec<&str> = r.split(['/', '\\']).collect(); + let unsafe_ref = Path::new(r).is_absolute() + || r.starts_with('/') + || r.starts_with('\\') + || segments.iter().any(|s| s.is_empty() || *s == ".."); + if unsafe_ref { + continue; + } + for d in dirs { + let mut p = d.clone(); + for (i, s) in segments.iter().enumerate() { + if i == segments.len() - 1 { + p.push(format!("{s}{MUSTACHE}")); + } else { + p.push(s); + } + } + if let Ok(text) = std::fs::read_to_string(&p) { + if let Some(id) = n["id"].as_str() { + out.insert(id.to_string(), text); + } + break; + } + } + } + out +} diff --git a/server/rust/metaobjects-codegen/src/eject.rs b/server/rust/metaobjects-codegen/src/eject.rs index b258316b92..259161acbc 100644 --- a/server/rust/metaobjects-codegen/src/eject.rs +++ b/server/rust/metaobjects-codegen/src/eject.rs @@ -50,6 +50,10 @@ pub struct Reference { /// unless asked, and a project with no list does not run it. The transport is one: it /// brings a web framework into the build. pub opt_in: bool, + /// Listed and run like any other, never ejected: the generator is engine and what an + /// adopter owns is something it reads (the shared registry's eject exemption). `source` is + /// empty, and `gen --list` marks it `[package-only]`. + pub package_only: bool, /// One line for `gen --list`. pub summary: &'static str, /// The shipped source, which is also the owned copy's text. @@ -79,6 +83,7 @@ pub const REFERENCES: &[Reference] = &[ name: "entity", tier: "native", opt_in: false, + package_only: false, layer: "model", module: "entity", type_name: "EntityGenerator", @@ -91,6 +96,7 @@ pub const REFERENCES: &[Reference] = &[ name: "rules-names", tier: "native", opt_in: false, + package_only: false, layer: "model", module: "rules_names", type_name: "RulesNamesGenerator", @@ -104,6 +110,7 @@ pub const REFERENCES: &[Reference] = &[ name: "contract-types", tier: "native", opt_in: false, + package_only: false, layer: "model", module: "contract_types", type_name: "ContractTypesGenerator", @@ -117,6 +124,7 @@ pub const REFERENCES: &[Reference] = &[ name: "repository", tier: "native", opt_in: false, + package_only: false, layer: "persistence", module: "repository", type_name: "RepositoryGenerator", @@ -130,6 +138,7 @@ pub const REFERENCES: &[Reference] = &[ name: "service", tier: "native", opt_in: false, + package_only: false, layer: "service", module: "service", type_name: "ServiceGenerator", @@ -144,6 +153,7 @@ pub const REFERENCES: &[Reference] = &[ name: "service-routes", tier: "native", opt_in: true, + package_only: false, layer: "api", module: "service_routes", type_name: "ServiceRoutesGenerator", @@ -164,6 +174,7 @@ pub const REFERENCES: &[Reference] = &[ name: "client", tier: "native", opt_in: false, + package_only: false, layer: "client", module: "client", type_name: "ClientGenerator", @@ -176,6 +187,7 @@ pub const REFERENCES: &[Reference] = &[ name: "commands", tier: "native", opt_in: false, + package_only: false, layer: "client", module: "commands", type_name: "CommandsGenerator", @@ -188,6 +200,7 @@ pub const REFERENCES: &[Reference] = &[ name: "render-helper", tier: "native", opt_in: false, + package_only: false, layer: "capability", module: "render_helper", type_name: "RenderHelperGenerator", @@ -201,6 +214,7 @@ pub const REFERENCES: &[Reference] = &[ name: "output-parser", tier: "native", opt_in: false, + package_only: false, layer: "capability", module: "output_parser", type_name: "OutputParserGenerator", @@ -214,6 +228,7 @@ pub const REFERENCES: &[Reference] = &[ name: "output-prompt", tier: "native", opt_in: false, + package_only: false, layer: "capability", module: "output_prompt", type_name: "OutputPromptGenerator", @@ -226,6 +241,7 @@ pub const REFERENCES: &[Reference] = &[ name: "metamodel-docs", tier: "neutral", opt_in: true, + package_only: false, layer: "docs", module: "metamodel_docs", type_name: "MetamodelDocsGenerator", @@ -235,6 +251,20 @@ pub const REFERENCES: &[Reference] = &[ (reads no model; templates/metamodel/ in the project wins)", source: include_str!("metamodel_docs.rs"), }, + Reference { + name: "docs-site", + tier: "neutral", + opt_in: true, + package_only: true, + layer: "docs", + module: "docs_site", + type_name: "DocsSiteGenerator", + needs: &[], + summary: "the model explorer: one browser app over the docs view (explorer.json), with \ + each node's generated files; run last. Own its theme in codegen/docs-site/ \ + (assets/explorer.css, assets/explorer.js, templates/explorer-*.mustache)", + source: "", + }, ]; /// The shipped generator of that name. @@ -245,6 +275,7 @@ pub fn reference(name: &str) -> Option<&'static Reference> { fn names_list() -> String { REFERENCES .iter() + .filter(|r| !r.package_only) .map(|r| r.name) .collect::>() .join(", ") @@ -320,6 +351,7 @@ pub struct OwnedCopy { pub fn owned_copies(project_root: &Path) -> Vec { REFERENCES .iter() + .filter(|r| !r.package_only) .filter_map(|r| { let text = std::fs::read_to_string(project_root.join(r.owned_path())).ok()?; Some(OwnedCopy { @@ -371,6 +403,20 @@ fn io(what: &str, path: &Path, e: &std::io::Error) -> EjectError { } fn resolve(names: &[String]) -> Result, EjectError> { + let package_only: Vec<&str> = names + .iter() + .map(String::as_str) + .filter(|n| reference(n).is_some_and(|r| r.package_only)) + .collect(); + if !package_only.is_empty() { + return Err(EjectError::Usage(format!( + "{} stays in the package and has no copy to eject: what a project owns is what it \ + reads (for docs-site, its theme under {}/); ejectable: {}", + package_only.join(", "), + crate::docs_site::OWNED_DOCS_SITE_DIR, + names_list() + ))); + } let unknown: Vec<&str> = names .iter() .map(String::as_str) diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index db01261e30..6a8f9ccd24 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -17,6 +17,8 @@ //! compares with disk (`compare`), and writes nothing at all. use std::collections::{BTreeMap, HashSet}; + +use serde_json::{Map, Value}; use std::path::{Path, PathBuf}; use std::time::Instant; @@ -758,26 +760,52 @@ fn prepare<'g>( }) } -/// Run the selected generators in memory. Two files claiming one path is an error. -fn render(p: &mut Prepared<'_>, opts: &RunOptions) -> Result, RunError> { +/// A file a generator emitted, with the name of the generator that emitted it. +struct Rendered { + file: EmittedFile, + generated_by: String, +} + +/// Run the selected generators in memory. Two files claiming one path is an error. A +/// generator that reads the run's output runs after every other, and sees what they +/// emitted plus what the manifest records outside this run. +fn render(p: &mut Prepared<'_>, opts: &RunOptions) -> Result, RunError> { let start = Instant::now(); - let ctx = GenContext { + let mut ctx = GenContext { tree: &p.loaded.result.tree, root: p.loaded.result.root, entities: &opts.entities, collection: &p.loaded.collection, reference_nodes: &p.loaded.reference_nodes, + generated_files: None, }; - let mut emitted: Vec = Vec::new(); - for g in &p.selected { - emitted.extend(g.generate(&ctx).map_err(RunError::Generator)?); + let mut emitted: Vec = Vec::new(); + let emit = |g: &Selected<'_>, ctx: &GenContext<'_>, out: &mut Vec| { + let files = g.generate(ctx).map_err(RunError::Generator)?; + out.extend(files.into_iter().map(|file| Rendered { + file, + generated_by: g.name().to_string(), + })); + Ok::<(), RunError>(()) + }; + for g in p.selected.iter().filter(|g| !g.reads_run_output()) { + emit(g, &ctx, &mut emitted)?; + } + let readers: Vec<&Selected<'_>> = p.selected.iter().filter(|g| g.reads_run_output()).collect(); + let run_files; + if !readers.is_empty() { + run_files = generated_files(p, opts, &emitted); + ctx.generated_files = Some(&run_files); + for g in readers { + emit(g, &ctx, &mut emitted)?; + } } let mut seen: HashSet<&str> = HashSet::with_capacity(emitted.len()); - for f in &emitted { - if !seen.insert(f.path.as_str()) { + for r in &emitted { + if !seen.insert(r.file.path.as_str()) { return Err(RunError::Generator(GenError::new( ERR_PATH_COLLISION, - format!("two generated files claim the path {}", f.path), + format!("two generated files claim the path {}", r.file.path), ))); } } @@ -785,6 +813,43 @@ fn render(p: &mut Prepared<'_>, opts: &RunOptions) -> Result, R Ok(emitted) } +/// The generated files a reader of the run's output sees: every manifest entry that names +/// its generator and node, less the ones this run owns (under its output directory, unless +/// the run is narrowed and cannot tell), then this run's own files. +fn generated_files( + p: &Prepared<'_>, + opts: &RunOptions, + emitted: &[Rendered], +) -> Map { + let prefix = format!("{}/", p.out_rel); + let narrowed = narrowed(opts); + let mut out = Map::new(); + for (key, _) in p.manifest.records() { + if !narrowed && key.starts_with(&prefix) { + continue; + } + if let Some((by, node)) = p.manifest.provenance_of(key) { + out.insert(key.to_string(), provenance(by, Some(node))); + } + } + for r in emitted { + out.insert( + p.key_of(&r.file), + provenance(&r.generated_by, r.file.source_node.as_deref()), + ); + } + out +} + +fn provenance(generated_by: &str, source_node: Option<&str>) -> Value { + let mut o = Map::new(); + o.insert("generatedBy".into(), Value::String(generated_by.into())); + if let Some(n) = source_node { + o.insert("sourceNode".into(), Value::String(n.into())); + } + Value::Object(o) +} + /// Run `generators` over the project: the whole pipeline. pub fn run(opts: &RunOptions, generators: &[Box]) -> Result { let mut p = prepare(opts, generators)?; @@ -844,7 +909,8 @@ pub fn run(opts: &RunOptions, generators: &[Box]) -> Result = HashSet::new(); let mut written_hashes: BTreeMap = BTreeMap::new(); - for f in &emitted { + for r in &emitted { + let f = &r.file; let key = p.key_of(f); let path = p.project_root.join(&key); let fresh_hash = content_hash(&f.content); @@ -879,6 +945,8 @@ pub fn run(opts: &RunOptions, generators: &[Box]) -> Result return Err(io_error("reading", &path, &e)), } + p.manifest + .record_provenance(&key, &r.generated_by, f.source_node.as_deref()); written_hashes.insert(key, fresh_hash); } @@ -1035,7 +1103,8 @@ pub fn verify( let mut drifted = Vec::new(); let mut missing = Vec::new(); let mut emitted_keys: HashSet = HashSet::with_capacity(emitted.len()); - for f in &emitted { + for r in &emitted { + let f = &r.file; let key = p.key_of(f); let path = p.project_root.join(&key); match std::fs::read(&path) { diff --git a/server/rust/metaobjects-codegen/src/entity.rs b/server/rust/metaobjects-codegen/src/entity.rs index 08ab6a2e61..d80b755d97 100644 --- a/server/rust/metaobjects-codegen/src/entity.rs +++ b/server/rust/metaobjects-codegen/src/entity.rs @@ -269,10 +269,9 @@ fn model_crate( exports.extend(s.enums.iter().map(|e| e.type_name.clone())); lib_items.push((s.module(), exports)); let text = parts.struct_file(plan, s, cname, &q)?; - files.push(EmittedFile::new( - format!("{cname}/src/{}.rs", s.module()), - text, - )); + files.push( + EmittedFile::new(format!("{cname}/src/{}.rs", s.module()), text).from_node(&s.key), + ); } for (_, e) in &c.shared_enums { let module = module_name(&e.type_name); diff --git a/server/rust/metaobjects-codegen/src/generator.rs b/server/rust/metaobjects-codegen/src/generator.rs index d2338d2c71..c582a43182 100644 --- a/server/rust/metaobjects-codegen/src/generator.rs +++ b/server/rust/metaobjects-codegen/src/generator.rs @@ -9,13 +9,19 @@ use std::fmt; use metaobjects::collection::Collection; use metaobjects::node::{NodeId, Tree}; +use serde_json::{Map, Value}; -/// One generated file: its path relative to the output directory (always `/`-separated) -/// and its text. +/// One generated file: its path relative to the output directory (always `/`-separated), +/// its text and, for a file rendered from one node, that node's resolution key. #[derive(Debug, Clone, PartialEq, Eq)] pub struct EmittedFile { pub path: String, pub content: String, + /// The resolution key of the node this file was rendered from (`acme::shop::Order`), or + /// `None` for a file drawn from the whole model. The engine records it, with the + /// generator's name, in the hash manifest (`generatedBy`, `sourceNode`): the docs view + /// lists a node's files from it. + pub source_node: Option, } impl EmittedFile { @@ -23,8 +29,16 @@ impl EmittedFile { Self { path: path.into(), content: content.into(), + source_node: None, } } + + /// This file, rendered from the node whose resolution key is `key`. + #[must_use] + pub fn from_node(mut self, key: impl Into) -> Self { + self.source_node = Some(key.into()); + self + } } /// What a generator reads: the loaded model, the project's settings and the run's entity @@ -39,6 +53,11 @@ pub struct GenContext<'a> { pub collection: &'a Collection, /// Resolution keys of the nodes only reference sources declare (computed once at load). pub reference_nodes: &'a BTreeSet, + /// The generated files a generator that reads the run's output sees + /// ([`Generator::reads_run_output`]): project-relative path to + /// `{ generatedBy, sourceNode }`, this run's and the ones the manifest records outside + /// it. `None` for every other generator, and outside a run. + pub generated_files: Option<&'a Map>, } /// A generator failed: a shared-style error code and a message for people. @@ -150,6 +169,13 @@ pub trait Generator { Err(unknown_options(self.name(), options, &[])) } + /// Whether this generator reads what the rest of the run generated + /// ([`GenContext::generated_files`]). The engine runs every such generator after every + /// other, so a write run and `verify` list the same files. + fn reads_run_output(&self) -> bool { + false + } + /// Produce the generator's files for the loaded model. fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError>; } diff --git a/server/rust/metaobjects-codegen/src/hashes.rs b/server/rust/metaobjects-codegen/src/hashes.rs index 344609ae95..725c240d4c 100644 --- a/server/rust/metaobjects-codegen/src/hashes.rs +++ b/server/rust/metaobjects-codegen/src/hashes.rs @@ -32,6 +32,9 @@ pub const HASHES_DIR: &str = ".hashes"; pub const ROOT_FILE: &str = ".root.json"; const PACKAGE_SEP: &str = "::"; +const HASH_FIELD: &str = "hash"; +const GENERATED_BY_FIELD: &str = "generatedBy"; +const SOURCE_NODE_FIELD: &str = "sourceNode"; const GITIGNORE_RULE: &str = ".gen-state/*"; const GITIGNORE_LEGACY: &str = "!.gen-state/.hashes.json"; const GITIGNORE_DIR: &str = "!.gen-state/.hashes/"; @@ -44,7 +47,7 @@ pub fn content_hash(content: &str) -> String { fn entry_hash(value: &Value) -> Option<&str> { match value { Value::String(s) => Some(s), - Value::Object(o) => o.get("hash").and_then(Value::as_str), + Value::Object(o) => o.get(HASH_FIELD).and_then(Value::as_str), _ => None, } } @@ -78,7 +81,7 @@ pub fn package_file_name(package: Option<&str>) -> String { pub fn place(path: &str, entry: &Value, objects: &[(String, String)]) -> Option { if let Some(node) = entry .as_object() - .and_then(|o| o.get("sourceNode")) + .and_then(|o| o.get(SOURCE_NODE_FIELD)) .and_then(Value::as_str) { let object = node.split('.').next().unwrap_or(node); @@ -305,7 +308,7 @@ impl HashManifest { } match self.entries.get_mut(key) { Some(Value::Object(o)) => { - o.insert("hash".into(), Value::String(hash.into())); + o.insert(HASH_FIELD.into(), Value::String(hash.into())); } _ => { self.entries.insert(key.into(), Value::String(hash.into())); @@ -314,6 +317,59 @@ impl HashManifest { self.dirty = true; } + /// Record which generator wrote `key` and, for a file rendered from one node, that + /// node's resolution key (the docs view's `files`). With a source node the entry becomes + /// `{ hash, , generatedBy, sourceNode }`; without one it returns to + /// the plain hash, or to `{ hash, }`. A path with no recorded hash is left + /// alone: provenance never records a write. A no-op when nothing changes. + pub fn record_provenance(&mut self, key: &str, generated_by: &str, source_node: Option<&str>) { + let Some(current) = self.entries.get(key) else { + return; + }; + let Some(hash) = entry_hash(current).map(str::to_string) else { + return; + }; + let mut next = Map::new(); + next.insert(HASH_FIELD.into(), Value::String(hash.clone())); + if let Value::Object(o) = current { + for (k, v) in o { + if k != HASH_FIELD && k != GENERATED_BY_FIELD && k != SOURCE_NODE_FIELD { + next.insert(k.clone(), v.clone()); + } + } + } + if let Some(node) = source_node { + next.insert( + GENERATED_BY_FIELD.into(), + Value::String(generated_by.into()), + ); + next.insert(SOURCE_NODE_FIELD.into(), Value::String(node.into())); + } + let next = if next.len() == 1 { + Value::String(hash) + } else { + Value::Object(next) + }; + if self.entries.get(key) != Some(&next) { + self.entries.insert(key.into(), next); + self.dirty = true; + } + } + + /// The generator and source node recorded for `key`, when it has both. + pub fn provenance_of(&self, key: &str) -> Option<(&str, &str)> { + let o = self.entries.get(key)?.as_object()?; + Some(( + o.get(GENERATED_BY_FIELD)?.as_str()?, + o.get(SOURCE_NODE_FIELD)?.as_str()?, + )) + } + + /// Every recorded entry as the docs view reads the manifest: path to its raw entry. + pub fn entries(&self) -> &Map { + &self.entries + } + /// Drop the record for `key`. pub fn remove(&mut self, key: &str) { if self.entries.shift_remove(key).is_some() { diff --git a/server/rust/metaobjects-codegen/src/lib.rs b/server/rust/metaobjects-codegen/src/lib.rs index 873f651361..5d4b11d5e6 100644 --- a/server/rust/metaobjects-codegen/src/lib.rs +++ b/server/rust/metaobjects-codegen/src/lib.rs @@ -21,6 +21,7 @@ extern crate self as metaobjects_codegen; pub mod client; pub mod commands; pub mod contract_types; +pub mod docs_site; pub mod eject; pub mod emitted; pub mod engine; @@ -49,6 +50,7 @@ pub mod writer; pub use client::ClientGenerator; pub use commands::CommandsGenerator; pub use contract_types::ContractTypesGenerator; +pub use docs_site::DocsSiteGenerator; pub use engine::{ Change, ChangeKind, ExtraFile, FileCounts, Outcome, Refusal, RunError, RunOptions, RunReport, VerifyReport, run, verify, @@ -82,5 +84,6 @@ pub fn shipped_generators() -> Vec> { Box::new(OutputParserGenerator), Box::new(OutputPromptGenerator), Box::new(MetamodelDocsGenerator), + Box::new(DocsSiteGenerator), ] } diff --git a/server/rust/metaobjects-codegen/src/output_parser.rs b/server/rust/metaobjects-codegen/src/output_parser.rs index 3e148cc7bd..3af022f4e3 100644 --- a/server/rust/metaobjects-codegen/src/output_parser.rs +++ b/server/rust/metaobjects-codegen/src/output_parser.rs @@ -168,6 +168,8 @@ pub fn render( /// What one prompt's parser needs. pub struct ParserPlan { pub template: String, + /// The template's resolution key: the node its file is rendered from. + pub key: String, pub module: String, pub response_name: String, pub response_crate: String, @@ -205,6 +207,7 @@ fn parser_of( let format = reply_format(tree, t); Ok(ParserPlan { template: n.name.clone(), + key: tree.resolution_key(t), module: snake(&n.name), response_name: tree.node(response).name.clone(), response_crate: s.crate_name.clone(), @@ -230,10 +233,10 @@ fn parsers_crate( files: &mut Vec, ) -> Result<(), GenError> { for p in &c.parsers { - files.push(EmittedFile::new( - format!("{name}/src/{}.rs", p.module), - parts.parser_file(p)?, - )); + files.push( + EmittedFile::new(format!("{name}/src/{}.rs", p.module), parts.parser_file(p)?) + .from_node(&p.key), + ); } files.push(EmittedFile::new( format!("{name}/Cargo.toml"), diff --git a/server/rust/metaobjects-codegen/src/output_prompt.rs b/server/rust/metaobjects-codegen/src/output_prompt.rs index 59c54ea993..46138f3f17 100644 --- a/server/rust/metaobjects-codegen/src/output_prompt.rs +++ b/server/rust/metaobjects-codegen/src/output_prompt.rs @@ -155,6 +155,8 @@ pub fn render( /// What one prompt's fragment needs. pub struct FragmentPlan { pub template: String, + /// The template's resolution key: the node its file is rendered from. + pub key: String, pub module: String, pub response: NodeId, pub response_name: String, @@ -166,6 +168,7 @@ fn fragment_of(tree: &Tree, index: &ObjectIndex, t: NodeId) -> Option( files: &mut Vec, ) -> Result<(), GenError> { for f in &c.fragments { - files.push(EmittedFile::new( - format!("{name}/src/{}.rs", f.module), - parts.fragment_file(f)?, - )); + files.push( + EmittedFile::new( + format!("{name}/src/{}.rs", f.module), + parts.fragment_file(f)?, + ) + .from_node(&f.key), + ); } files.push(EmittedFile::new( format!("{name}/Cargo.toml"), diff --git a/server/rust/metaobjects-codegen/src/render_helper.rs b/server/rust/metaobjects-codegen/src/render_helper.rs index 4b55c05862..270fc79010 100644 --- a/server/rust/metaobjects-codegen/src/render_helper.rs +++ b/server/rust/metaobjects-codegen/src/render_helper.rs @@ -360,6 +360,8 @@ pub struct PartPlan<'t> { /// What one template's helper needs. pub struct HelperPlan<'t> { pub template: String, + /// The template's resolution key: the node its file is rendered from. + pub key: String, pub function: String, pub module: String, pub is_email: bool, @@ -435,6 +437,7 @@ fn helper_of<'t>( let module = snake(&n.name); Ok(HelperPlan { template: n.name.clone(), + key: tree.resolution_key(t), function: format!("render_{module}"), module, is_email, @@ -539,10 +542,10 @@ fn prompts_crate( ) -> Result<(), GenError> { let mut modules: Vec<(&str, &str)> = Vec::new(); for h in &c.helpers { - files.push(EmittedFile::new( - format!("{name}/src/{}.rs", h.module), - parts.helper_file(h)?, - )); + files.push( + EmittedFile::new(format!("{name}/src/{}.rs", h.module), parts.helper_file(h)?) + .from_node(&h.key), + ); modules.push((&h.module, &h.function)); } modules.sort(); diff --git a/server/rust/metaobjects-codegen/src/repository.rs b/server/rust/metaobjects-codegen/src/repository.rs index 25d5076128..427c9a62a2 100644 --- a/server/rust/metaobjects-codegen/src/repository.rs +++ b/server/rust/metaobjects-codegen/src/repository.rs @@ -130,10 +130,13 @@ pub fn render( let mut files = Vec::new(); for sc in stored_crates_in(ctx, &plan)? { for e in &sc.entities { - files.push(EmittedFile::new( - format!("{}/src/{}.rs", sc.name, e.module), - parts.entity_file(e)?, - )); + files.push( + EmittedFile::new( + format!("{}/src/{}.rs", sc.name, e.module), + parts.entity_file(e)?, + ) + .from_node(ctx.tree.resolution_key(e.node)), + ); } let mut modules: Vec = sc.entities.iter().map(|e| e.module.clone()).collect(); modules.sort(); diff --git a/server/rust/metaobjects-codegen/src/service.rs b/server/rust/metaobjects-codegen/src/service.rs index bca985f1a7..d4bdd8b1b8 100644 --- a/server/rust/metaobjects-codegen/src/service.rs +++ b/server/rust/metaobjects-codegen/src/service.rs @@ -130,10 +130,13 @@ pub fn render( files.push(file("rustfmt.toml", RUSTFMT_TOML.to_string())); files.push(file("src/lib.rs", parts.lib_file(&s))); for e in &s.entities { - files.push(file( - &format!("src/{}.rs", e.store.module), - parts.entity_file(&s, e), - )); + files.push( + file( + &format!("src/{}.rs", e.store.module), + parts.entity_file(&s, e), + ) + .from_node(ctx.tree.resolution_key(e.store.node)), + ); } if !s.operations.is_empty() { files.push(file("src/operations.rs", parts.operations_file(&s))); diff --git a/server/rust/metaobjects-codegen/src/service_routes.rs b/server/rust/metaobjects-codegen/src/service_routes.rs index 9b2a3750be..766729139d 100644 --- a/server/rust/metaobjects-codegen/src/service_routes.rs +++ b/server/rust/metaobjects-codegen/src/service_routes.rs @@ -425,8 +425,14 @@ pub fn render( files.push(file("rustfmt.toml", RUSTFMT_TOML.to_string())); files.push(file("src/lib.rs", parts.lib_file(&r))); for e in &r.entities { - let module = &r.service.entities[e.index].store.module; - files.push(file(&format!("src/{module}.rs"), parts.entity_file(&r, e))); + let store = &r.service.entities[e.index].store; + files.push( + file( + &format!("src/{}.rs", store.module), + parts.entity_file(&r, e), + ) + .from_node(ctx.tree.resolution_key(store.node)), + ); } } if !files.is_empty() { diff --git a/server/rust/metaobjects-codegen/tests/common/mod.rs b/server/rust/metaobjects-codegen/tests/common/mod.rs index 53bcc1bd69..38f28dedf3 100644 --- a/server/rust/metaobjects-codegen/tests/common/mod.rs +++ b/server/rust/metaobjects-codegen/tests/common/mod.rs @@ -180,12 +180,13 @@ pub fn cargo(dir: &Path, args: &[&str]) -> std::process::Output { .expect("cargo runs") } -/// The shipped generators that write crates: every one but `metamodel-docs`, whose Markdown -/// pages are not a crate and are held to their own corpus (`tests/metamodel_docs.rs`). +/// The shipped generators that write crates: every one but the two docs generators, +/// `metamodel-docs` and `docs-site`, whose pages are not a crate. Each is held to its own corpus +/// (`tests/metamodel_docs.rs`, `tests/docs_site.rs`). pub fn crate_generators() -> Vec> { shipped_generators() .into_iter() - .filter(|g| g.name() != "metamodel-docs") + .filter(|g| !matches!(g.name(), "metamodel-docs" | "docs-site")) .collect() } diff --git a/server/rust/metaobjects-codegen/tests/docs_site.rs b/server/rust/metaobjects-codegen/tests/docs_site.rs new file mode 100644 index 0000000000..dba9c2ba74 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/docs_site.rs @@ -0,0 +1,231 @@ +//! The `docs-site` generator: the model explorer app over the docs view, the same bytes as the +//! other ports write (`fixtures/explorer-conformance/`, the repository's `explorer-app/`). + +mod common; + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use common::Scratch; +use metaobjects_codegen::docs_site::{ + APP_FILES, MODEL_FILE, STAMP_FILE, SiteInput, THEME_ASSETS, VIEW_FILE, emit, model_script, + read_prompt_texts, +}; +use metaobjects_codegen::sha256::sha256_hex; +use metaobjects_codegen::{RunOptions, run, shipped_generators, verify}; +use serde_json::Value; + +fn repo() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..") +} + +fn fixture(name: &str) -> PathBuf { + repo().join("fixtures/explorer-conformance").join(name) +} + +fn expected_view(name: &str) -> Value { + serde_json::from_str(&std::fs::read_to_string(fixture(name).join("expected.json")).unwrap()) + .unwrap() +} + +fn read(p: &Path) -> String { + std::fs::read_to_string(p).unwrap_or_else(|e| panic!("{}: {e}", p.display())) +} + +#[test] +fn the_model_script_is_typescripts_bytes() { + let texts = BTreeMap::from([ + ("b".to_string(), "B\n".to_string()), + ("a".to_string(), "A é".to_string()), + ]); + let templates = BTreeMap::from([("explorer-head.mustache".to_string(), "".to_string())]); + let (script, stamp) = model_script( + "Shop \u{2028}", + "v1", + &texts, + &templates, + &expected_view("shop"), + ); + // The title carries U+2028, which JSON.stringify leaves unescaped. + // explorerModelScript({ title: "Shop \u2028", footer: "v1", texts, templates, view }) in + // @metaobjectsdev/docs-site, over the same shop view, gives this stamp and these bytes. + assert_eq!(stamp, "05b57283a47416e2"); + assert_eq!( + sha256_hex(script.as_bytes()), + "02f2d4321101c0ab9fa9e22db542ff8f71f1e952748e8f894d388bd43feeb6bc" + ); + assert_eq!( + metaobjects::docs_view::stamp_script(&stamp), + "window.MO_STAMP = \"05b57283a47416e2\";\n" + ); +} + +#[test] +fn the_site_is_the_shared_app_and_the_views_bytes() { + let view = expected_view("model-alone"); + let files = emit(&SiteInput { + view: &view, + title: "t", + footer: "", + texts: &BTreeMap::new(), + assets_dir: None, + templates_dir: None, + }) + .unwrap(); + let by_path: BTreeMap<&str, &str> = files + .iter() + .map(|(p, t)| (p.as_str(), t.as_str())) + .collect(); + for (path, _) in APP_FILES { + assert_eq!( + by_path[path], + read(&repo().join("explorer-app").join(path)), + "{path}: the crate's copy is the repository's" + ); + } + assert_eq!( + by_path[VIEW_FILE], + read(&fixture("model-alone").join("expected.json")) + ); + let order: Vec<&str> = files.iter().map(|(p, _)| p.as_str()).collect(); + assert_eq!( + order, + [ + "index.html", + "assets/explorer-app.js", + "assets/cytoscape.min.js", + "assets/3d-force-graph.min.js", + "assets/explorer.css", + "assets/explorer.js", + MODEL_FILE, + STAMP_FILE, + VIEW_FILE, + ] + ); +} + +#[test] +fn an_owned_theme_replaces_the_shipped_one() { + let s = Scratch::new("docs-site-theme"); + s.write("assets/explorer.css", "body{}"); + s.write("templates/explorer-head.mustache", ""); + let view = expected_view("model-alone"); + let files: BTreeMap = emit(&SiteInput { + view: &view, + title: "t", + footer: "", + texts: &BTreeMap::new(), + assets_dir: Some(s.path().join("assets")), + templates_dir: Some(s.path().join("templates")), + }) + .unwrap() + .into_iter() + .collect(); + assert_eq!(files["assets/explorer.css"], "body{}"); + assert_eq!( + files["assets/explorer.js"], + read(&repo().join("explorer-app/assets/explorer.js")), + "a theme file the project does not own stays the shipped one" + ); + assert!( + files[MODEL_FILE].contains("\"templates\":{\"explorer-head.mustache\":\"\"}"), + "the owned template is carried" + ); + assert_eq!(THEME_ASSETS, ["explorer.css", "explorer.js"]); +} + +#[test] +fn prompt_texts_are_read_by_text_ref_and_never_outside_the_dirs() { + let view = expected_view("shop"); + let dirs = [fixture("shop").join("project/prompts")]; + let texts = read_prompt_texts(&view, &dirs); + assert_eq!(texts.len(), 1, "{texts:?}"); + assert_eq!( + texts.values().next().unwrap(), + &read(&fixture("shop").join("project/prompts/shop/order-note.mustache")) + ); + let climbing: Value = serde_json::json!({ "nodes": [ + { "id": "x", "attrs": [{ "name": "textRef", "value": "../shop/order-note" }] }, + { "id": "y", "attrs": [{ "name": "textRef", "value": "/etc/passwd" }] } + ] }); + assert!( + read_prompt_texts(&climbing, &[fixture("shop").join("project/prompts/shop")]).is_empty() + ); +} + +/// Copy a directory tree. +fn copy_dir(from: &Path, to: &Path) { + for e in std::fs::read_dir(from).unwrap().flatten() { + let dest = to.join(e.file_name()); + if e.path().is_dir() { + std::fs::create_dir_all(&dest).unwrap(); + copy_dir(&e.path(), &dest); + } else { + std::fs::copy(e.path(), dest).unwrap(); + } + } +} + +#[test] +fn a_run_writes_the_explorer_over_the_files_the_manifest_records() { + let p = Scratch::project("docs-site-run", &[]); + copy_dir(&fixture("shop").join("project"), p.path()); + for f in ["verify.json", "routes.json"] { + std::fs::copy(fixture("shop").join(f), p.path().join(f)).unwrap(); + } + // The fixture's hashes.json, as the legacy single-file manifest a project may still hold: + // its files are under src/, outside this run's output directory, so the site lists them. + p.write( + ".metaobjects/.gen-state/.hashes.json", + &read(&fixture("shop").join("hashes.json")), + ); + p.write( + "metaobjects.config.json", + r#"{ "generators": [{ "name": "docs-site", "options": { + "subDir": "", "prompts": "prompts", "verifyFile": "verify.json", "routesFile": "routes.json" + } }] }"#, + ); + let mut opts = RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); + + assert_eq!( + p.read("generated/explorer.json"), + read(&fixture("shop").join("expected.json")), + "the run's explorer.json is the conformance view" + ); + let model = p.read("generated/explorer-model.js"); + assert!( + model.starts_with("window.MO_MODEL = {\"stamp\":"), + "{}", + &model[..40] + ); + assert!(model.contains("\"title\":\""), "a title"); + assert!( + model.contains("\"texts\":{\""), + "the prompt text is carried" + ); + for (path, _) in APP_FILES { + assert!(p.exists(&format!("generated/{path}")), "{path}"); + } + let report = + verify(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("verify failed: {e}")); + assert!( + report.drifted.is_empty() && report.missing.is_empty(), + "verify lists the same files the run wrote: {:?} {:?}", + report.drifted, + report.missing + ); +} + +#[test] +fn a_project_with_no_list_does_not_run_it() { + let p = Scratch::project("docs-site-unlisted", &common::shop_files()); + let mut opts = RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); + assert!( + !p.exists("generated/site/explorer.json"), + "docs-site is opt-in" + ); +} diff --git a/server/rust/metaobjects-codegen/tests/entity_edges.rs b/server/rust/metaobjects-codegen/tests/entity_edges.rs index 6002d6c26e..42d3ac1d81 100644 --- a/server/rust/metaobjects-codegen/tests/entity_edges.rs +++ b/server/rust/metaobjects-codegen/tests/entity_edges.rs @@ -27,6 +27,7 @@ fn generate_named( entities: &names, collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; EntityGenerator .generate(&ctx) diff --git a/server/rust/metaobjects-codegen/tests/generator_registry.rs b/server/rust/metaobjects-codegen/tests/generator_registry.rs index cd646fc149..ac9e0f2052 100644 --- a/server/rust/metaobjects-codegen/tests/generator_registry.rs +++ b/server/rust/metaobjects-codegen/tests/generator_registry.rs @@ -69,16 +69,29 @@ fn completeness_every_generator_ships_eject_source_in_run_order() { let registry = registry(); let generators = shipped_generators(); let shipped: Vec<&str> = generators.iter().map(|g| g.name()).collect(); - let ejectable: Vec<&str> = REFERENCES.iter().map(|r| r.name).collect(); + let listed: Vec<&str> = REFERENCES.iter().map(|r| r.name).collect(); assert_eq!( - ejectable, shipped, - "`eject` offers exactly the shipped generators, in run order" + listed, shipped, + "`eject` knows exactly the shipped generators, in run order" ); for (name, entry) in expected(®istry) { - assert_eq!( - entry["eject"], "full", - "{name}: the Rust port has no eject exemption" - ); + let r = REFERENCES.iter().find(|r| r.name == name).unwrap(); + if r.package_only { + // An exemption is the shared file's ruling, with its reason; the port only follows it. + assert!( + entry["eject"]["exempt"].is_string() && entry["eject"]["ruling"].is_string(), + "{name}: package-only here, but the registry does not exempt it" + ); + assert!( + r.source.is_empty(), + "{name}: a package-only generator ships no copy" + ); + } else { + assert_eq!( + entry["eject"], "full", + "{name}: ejectable here, but the registry exempts it" + ); + } } let pending = registry["eject"]["pending"].as_array().unwrap(); assert!( @@ -153,7 +166,7 @@ fn depth_an_owned_copy_names_nothing_outside_the_engine_surface() { exported_engine_modules(), "the registry's engine surface and the modules the crate exports differ; edit both together" ); - for r in REFERENCES { + for r in REFERENCES.iter().filter(|r| !r.package_only) { assert!( !engine.contains(r.module), "{}: a generator's own module is not engine", diff --git a/server/rust/metaobjects-codegen/tests/golden.rs b/server/rust/metaobjects-codegen/tests/golden.rs index 7104e5004e..a0c7a36f44 100644 --- a/server/rust/metaobjects-codegen/tests/golden.rs +++ b/server/rust/metaobjects-codegen/tests/golden.rs @@ -27,6 +27,7 @@ fn generate(files: &[(&str, &str)]) -> BTreeMap { entities: &[], collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; common::crate_generators() .iter() @@ -116,6 +117,7 @@ fn the_support_crate_is_the_emitted_modules() { entities: &[], collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; let files = EntityGenerator .generate(&ctx) diff --git a/server/rust/metaobjects-codegen/tests/hash_manifest.rs b/server/rust/metaobjects-codegen/tests/hash_manifest.rs index fd78bce477..b87d6846ee 100644 --- a/server/rust/metaobjects-codegen/tests/hash_manifest.rs +++ b/server/rust/metaobjects-codegen/tests/hash_manifest.rs @@ -158,6 +158,62 @@ fn a_legacy_manifest_splits_exactly_as_the_vector_says() { let _ = std::fs::remove_dir_all(&root); } +#[test] +fn provenance_follows_the_vectors() { + let v = vectors(); + let prov = &v["provenance"]; + let root = scratch("provenance"); + let gs = gen_state(&root); + std::fs::create_dir_all(gs.join(HASHES_DIR)).unwrap(); + for (name, entries) in prov["beforeFiles"].as_object().unwrap() { + let mut text = serde_json::to_string_pretty(entries).unwrap(); + text.push('\n'); + std::fs::write(gs.join(HASHES_DIR).join(name), text).unwrap(); + } + let record = |gs: &Path| { + let mut m = HashManifest::load(gs); + m.set_objects(objects(&v)); + for r in prov["records"].as_array().unwrap() { + m.record_provenance( + r["path"].as_str().unwrap(), + r["generatedBy"].as_str().unwrap(), + r["sourceNode"].as_str(), + ); + } + m.save().unwrap() + }; + assert!(record(&gs)); + let got = files_of(&gs); + let want = prov["afterFiles"].as_object().unwrap(); + let mut want_names: Vec<&String> = want.keys().collect(); + want_names.sort(); + assert_eq!(got.keys().collect::>(), want_names); + for (name, text) in &got { + // Byte-compare: field order inside an entry is part of the contract. + let mut expect = serde_json::to_string_pretty(&want[name]).unwrap(); + expect.push('\n'); + let parsed: Value = serde_json::from_str(&expect).unwrap(); + let sorted: Map = { + let mut keys: Vec<_> = parsed.as_object().unwrap().keys().cloned().collect(); + keys.sort(); + keys.into_iter() + .map(|k| (k.clone(), parsed[&k].clone())) + .collect() + }; + let mut expect = serde_json::to_string_pretty(&Value::Object(sorted)).unwrap(); + expect.push('\n'); + assert_eq!(text, &expect, "{name}"); + } + let golden = prov["goldenFile"].as_str().unwrap(); + assert_eq!(got[golden], prov["goldenText"].as_str().unwrap()); + + // Recording the same records again changes no file. + let before = files_of(&gs); + assert!(!record(&gs), "a second identical recording writes nothing"); + assert_eq!(files_of(&gs), before); + let _ = std::fs::remove_dir_all(&root); +} + #[test] fn the_gitignore_is_left_alone_when_it_has_the_line_or_no_rule() { let after = vectors()["legacySplit"]["gitignoreAfter"] diff --git a/server/rust/metaobjects-codegen/tests/list_query_conformance.rs b/server/rust/metaobjects-codegen/tests/list_query_conformance.rs index af75b4267e..8958ab6c00 100644 --- a/server/rust/metaobjects-codegen/tests/list_query_conformance.rs +++ b/server/rust/metaobjects-codegen/tests/list_query_conformance.rs @@ -60,6 +60,7 @@ fn ticket_spec() -> ListSpec { entities: &[], collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; let plan = Plan::of(&ctx).expect("the model plans"); let ticket = plan diff --git a/server/rust/metaobjects-codegen/tests/reference_nodes.rs b/server/rust/metaobjects-codegen/tests/reference_nodes.rs index 6867f2c878..4d64896b9c 100644 --- a/server/rust/metaobjects-codegen/tests/reference_nodes.rs +++ b/server/rust/metaobjects-codegen/tests/reference_nodes.rs @@ -44,6 +44,7 @@ fn a_reference_node_is_loaded_and_not_generated() { entities: &[], collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; let files = EntityGenerator.generate(&ctx).expect("generates"); let all: String = files.iter().map(|f| f.content.as_str()).collect(); diff --git a/server/rust/metaobjects-codegen/tests/rules_inert.rs b/server/rust/metaobjects-codegen/tests/rules_inert.rs index a4bb200eaf..ce7d41963e 100644 --- a/server/rust/metaobjects-codegen/tests/rules_inert.rs +++ b/server/rust/metaobjects-codegen/tests/rules_inert.rs @@ -51,6 +51,8 @@ enum Pick { DataAccess, Service, Transport, + /// The model explorer: it documents every node, so it is meant to show the rules. + Docs, } fn pick_of(name: &str) -> Pick { @@ -62,6 +64,8 @@ fn pick_of(name: &str) -> Pick { Pick::Service } else if TRANSPORT.contains(&name) { Pick::Transport + } else if name == "docs-site" { + Pick::Docs } else { Pick::Flat } @@ -87,6 +91,7 @@ fn emit(variant: &str, pick: Pick) -> BTreeMap { entities: &[], collection: &loaded.collection, reference_nodes: &loaded.reference_nodes, + generated_files: None, }; let mut files = BTreeMap::new(); for g in shipped_generators() { @@ -120,6 +125,18 @@ fn a_model_with_operations_and_transitions_generates_what_it_does_without_them() } } +#[test] +fn the_model_explorer_documents_operations_and_transitions() { + let with = emit("with", Pick::Docs); + let without = emit("without", Pick::Docs); + let view = "site/explorer.json"; + assert!(with.contains_key(view) && without.contains_key(view)); + assert_ne!( + with[view], without[view], + "the explorer lists the rules nodes" + ); +} + #[test] fn the_rules_layer_generators_write_nothing_without_the_vocabulary_and_only_their_own_files_with_it() { diff --git a/server/rust/metaobjects-codegen/tests/run_engine.rs b/server/rust/metaobjects-codegen/tests/run_engine.rs index 6bca97644f..94775c95e4 100644 --- a/server/rust/metaobjects-codegen/tests/run_engine.rs +++ b/server/rust/metaobjects-codegen/tests/run_engine.rs @@ -60,6 +60,25 @@ fn a_first_run_writes_every_file_and_records_them_all() { assert_eq!(names, [STAGE_LOAD, STAGE_PLAN, STAGE_RENDER, STAGE_WRITE]); } +#[test] +fn a_run_records_which_generator_and_node_each_file_came_from() { + let p = Scratch::project("provenance", &shop_files()); + gen_ok(&p); + let manifest: serde_json::Value = serde_json::from_str(&p.read(MANIFEST)).unwrap(); + let order = &manifest["generated/shop/src/order.rs"]; + assert_eq!(order["generatedBy"], "entity", "{manifest}"); + assert_eq!(order["sourceNode"], "shop::Order", "{manifest}"); + let root: serde_json::Value = + serde_json::from_str(&p.read(".metaobjects/.gen-state/.hashes/.root.json")).unwrap(); + assert!( + root["generated/shop/Cargo.toml"].is_string(), + "a whole-crate file is the plain hash: {root}" + ); + // A second run records the same thing and so writes no manifest. + let again = gen_with(&p, |o| o.force = true).unwrap(); + assert!(!again.manifest_written); +} + #[test] fn an_unchanged_project_skips_without_touching_any_file() { let p = Scratch::project("skip", &shop_files()); @@ -203,9 +222,10 @@ fn an_orphan_with_a_hand_edit_is_never_deleted_and_fails_the_run_by_name() { other => panic!("expected a refusal, got {other}"), } assert_eq!(p.read(orphan), "// mine\n", "the edit is left in place"); - // The object is gone, so nothing places the orphan any more: it is filed under the root. + // The object is gone, but the entry still names the node it was rendered from + // (`sourceNode`), and that places it: it stays in its package's manifest. assert!( - p.read(".metaobjects/.gen-state/.hashes/.root.json") + p.read(".metaobjects/.gen-state/.hashes/shop.billing.json") .contains(orphan), "and it stays recorded" ); diff --git a/server/rust/metaobjects/src/docs_view.rs b/server/rust/metaobjects/src/docs_view.rs new file mode 100644 index 0000000000..bf8feb95be --- /dev/null +++ b/server/rust/metaobjects/src/docs_view.rs @@ -0,0 +1,1431 @@ +//! The docs view of a loaded model: one port-neutral document, the facts every documentation +//! page reads and what the model explorer draws (`docs/features/docs-view.md`). +//! +//! The Rust port of TypeScript's `buildDocsView` (`@metaobjectsdev/metadata`, +//! `src/docs-view/build.ts`), held to the same bytes by `fixtures/explorer-conformance/`. It +//! reads the model the loader built and resolved, and re-derives none of it: ids and pages from +//! the effective tree walked once in declaration order ([`Tree::children`], the order the +//! effective canonical serializer writes); inheritance from a child whose parent is another +//! node; references from the loader's own resolution ([`reference_targets`], the node an +//! `extends` bound); claims through the rules the requirement gate uses. +//! +//! Three optional inputs add what the model does not hold, each as parsed JSON and each left +//! out when absent or malformed: the `meta verify --format json` payload, the generation +//! manifest (`path → { generatedBy, sourceNode }`) and the routes (`[{ node, method, path }]`). +//! The result is deterministic: [`serialize`] gives the same bytes for the same inputs. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; + +use serde_json::{Map, Value, json}; + +use crate::json::{js_quote, to_js_compact, to_js_pretty}; +use crate::loader::{is_ref_bearing_attr, reference_targets, split_child_tail}; +use crate::node::{NodeId, PACKAGE_SEP, Tree}; +use crate::parser::TYPE_OBJECT; +use crate::serializer::normalize; +use crate::validate::util::ObjectIndex; + +/// Bumped when a field changes meaning or is removed. +pub const FORMAT: &str = "metaobjects-docs-view/1"; + +const TYPE_REQUIREMENT: &str = "requirement"; +const TYPE_TEMPLATE: &str = "template"; +const TYPE_FIELD: &str = "field"; +const SUBTYPE_FUNCTIONAL: &str = "functional"; +const SUBTYPE_ARCHITECTURAL: &str = "architectural"; +const EXTENDS: &str = "extends"; +const ATTR_IS_ABSTRACT: &str = "isAbstract"; +const ATTR_IS_ARRAY: &str = "isArray"; +const ATTR_TITLE: &str = "title"; +const ATTR_DESCRIPTION: &str = "description"; +const ATTR_SUMMARY: &str = "summary"; +const ATTR_LEVEL: &str = "level"; +const ATTR_STATUS: &str = "status"; +const ATTR_DISPOSITION: &str = "disposition"; +const ATTR_TRACKED_BY: &str = "trackedBy"; +const ATTR_STATEMENT: &str = "statement"; +const ATTR_COUNTEREXAMPLE: &str = "counterexample"; +const ATTR_IMPLEMENTED_BY: &str = "implementedBy"; +/// The requirement statuses, in declaration order (the order the view counts them in). +const STATUSES: &[&str] = &["planned", "live", "partial", "retired"]; +/// The level from which a requirement links the model (`requirement.*` `@level` 4). +const LEVEL_OBJECT: i64 = 4; +const CODE_OBJECT_UNCLAIMED: &str = "WARN_REQUIREMENT_OBJECT_UNCLAIMED"; +const DOT: &str = "."; +const NUL: &str = "\u{0}"; + +/// The file's bytes: two-space JSON, as `JSON.stringify(view, null, 2)`, and one trailing +/// newline. +pub fn serialize(view: &Value) -> String { + let mut out = to_js_pretty(view); + out.push('\n'); + out +} + +/// What the explorer app's model script carries besides its stamp, as compact JSON +/// (`JSON.stringify({ title, footer, texts, templates, view })`), texts and templates in key +/// order. Its SHA-256 is the stamp ([`model_script`]). +pub fn model_payload( + title: &str, + footer: &str, + texts: &BTreeMap, + templates: &BTreeMap, + view: &Value, +) -> String { + let strings = |m: &BTreeMap| { + Value::Object( + m.iter() + .map(|(k, v)| (k.clone(), Value::String(v.clone()))) + .collect::>(), + ) + }; + let mut rest = Map::new(); + rest.insert("title".into(), Value::String(title.into())); + rest.insert("footer".into(), Value::String(footer.into())); + rest.insert("texts".into(), strings(texts)); + rest.insert("templates".into(), strings(templates)); + rest.insert("view".into(), view.clone()); + to_js_compact(&Value::Object(rest)) +} + +/// The explorer app's data script, `window.MO_MODEL = {"stamp":...,};` and a newline: +/// the bytes TypeScript's `explorerModelScript` writes. `stamp` is the first 16 hex digits of +/// the SHA-256 of `payload` ([`model_payload`]). +pub fn model_script(stamp: &str, payload: &str) -> String { + let body = payload.strip_prefix('{').unwrap_or(payload); + format!( + "window.MO_MODEL = {{\"stamp\":{},{body};\n", + js_quote(stamp) + ) +} + +/// The stamp file the open app polls, `window.MO_STAMP = "";` and a newline. +pub fn stamp_script(stamp: &str) -> String { + format!("window.MO_STAMP = {};\n", js_quote(stamp)) +} + +/// The docs view of the model alone. +pub fn build_model(tree: &Tree, root: NodeId) -> Value { + build(tree, root, None, None, None) +} + +/// Build the docs view of the model at `root`. `verify`, `manifest` and `routes` are optional; +/// a malformed one only leaves its part out. +pub fn build( + tree: &Tree, + root: NodeId, + verify: Option<&Value>, + manifest: Option<&Value>, + routes: Option<&Value>, +) -> Value { + Build::new(tree, root).run(verify, manifest, routes) +} + +// ---- the walk ------------------------------------------------------------------------------ + +/// A node as walked: where it sits, and the ids and pages it gets. Indexes are into +/// [`Build::walked`]. +struct Walked { + node: NodeId, + id: String, + plain: String, + top: usize, + parent: Option, + direct: Option, + requirement: Option, + order: usize, + canonical: bool, + declared_on: Option, + anchor: String, + path: String, + children: Vec, + address: String, +} + +/// One row of the verify payload's requirement ledger. +struct Ledger { + digest: String, + verdict: String, + diagnostics: Vec, + sup_ref: String, + sup_resolves: bool, + sup_target: String, + has_sup: bool, +} + +struct Build<'t> { + tree: &'t Tree, + root: NodeId, + objects: ObjectIndex, + walked: Vec, + tops: Vec, + by_id: HashMap, + canonical: HashMap, + by_plain: HashMap, + requirements: Vec, +} + +impl<'t> Build<'t> { + fn new(tree: &'t Tree, root: NodeId) -> Self { + let mut b = Self { + tree, + root, + objects: ObjectIndex::build(tree, root), + walked: Vec::new(), + tops: Vec::new(), + by_id: HashMap::new(), + canonical: HashMap::new(), + by_plain: HashMap::new(), + requirements: Vec::new(), + }; + b.walk(); + b + } + + fn walk(&mut self) { + let top_level: Vec = self.tree.children(self.root).to_vec(); + // Top-level nodes of different types may share a package and a name. The object keeps + // the plain id, since every reference in the model names an object, else the first + // declared; each other one is qualified by its type. + let mut holder: HashMap = HashMap::new(); + for &n in &top_level { + let id = self.plain_of(n); + let replace = match holder.get(&id) { + None => true, + Some(&held) => { + self.tree.node(held).type_name != TYPE_OBJECT + && self.tree.node(n).type_name == TYPE_OBJECT + } + }; + if replace { + holder.insert(id, n); + } + } + let mut seen: HashSet = HashSet::new(); + for (i, &n) in top_level.iter().enumerate() { + self.visit(n, i, None, "", &holder, &mut seen); + } + for i in 0..self.walked.len() { + self.walked[i].path = self.path_of(i); + } + } + + fn visit( + &mut self, + n: NodeId, + index: usize, + parent: Option, + req_prefix: &str, + holder: &HashMap, + seen: &mut HashSet, + ) { + let node = self.tree.node(n); + let name = node.name.as_str(); + let (mut id, plain) = match parent { + None => { + let plain = if name.is_empty() { + format!("#{index}") + } else { + self.plain_of(n) + }; + let mut id = plain.clone(); + let held = holder.get(&plain).copied(); + if !name.is_empty() + && held != Some(n) + && held.is_none_or(|h| self.tree.node(h).type_name != node.type_name) + { + id = qualified(&plain, self.tree, n); + } + (id, plain) + } + Some(p) => { + let pw = &self.walked[p]; + if name.is_empty() { + ( + format!("{}#{index}", pw.id), + format!("{}#{index}", pw.plain), + ) + } else { + ( + format!("{}{DOT}{name}", pw.id), + format!("{}{DOT}{name}", pw.plain), + ) + } + } + }; + // The first sibling of a name keeps the plain id; a later one of another type is + // qualified by type. + if parent.is_some() && !name.is_empty() && seen.contains(&id) { + id = qualified(&id, self.tree, n); + } + assert!( + !seen.contains(&id), + "docs view: two nodes share the id \"{id}\" — the model names two siblings alike" + ); + seen.insert(id.clone()); + let is_req = node.type_name == TYPE_REQUIREMENT; + let address = if is_req { + if req_prefix.is_empty() { + name.to_string() + } else { + format!("{req_prefix}{DOT}{name}") + } + } else { + req_prefix.to_string() + }; + let inherited = parent.is_some_and(|p| node.parent != Some(self.walked[p].node)); + let me = self.walked.len(); + let (top, direct, requirement, canonical) = match parent { + None => (me, None, is_req.then_some(me), true), + Some(p) => { + let pw = &self.walked[p]; + let direct = if pw.parent.is_none() { + Some(me) + } else { + pw.direct + }; + let requirement = if is_req { Some(me) } else { pw.requirement }; + (pw.top, direct, requirement, pw.canonical && !inherited) + } + }; + let anchor = if direct == Some(me) { + member_anchor(self.tree, n, name, index) + } else { + String::new() + }; + self.walked.push(Walked { + node: n, + id: id.clone(), + plain: plain.clone(), + top, + parent, + direct, + requirement, + order: index, + canonical, + declared_on: if inherited { node.parent } else { None }, + anchor, + path: String::new(), + children: Vec::new(), + address: if is_req { + address.clone() + } else { + String::new() + }, + }); + self.by_id.insert(id, me); + let top_w = &self.walked[top]; + if top_w.id == top_w.plain && !self.by_plain.contains_key(&plain) { + self.by_plain.insert(plain, me); + } + if canonical { + self.canonical.insert(n, me); + } + match parent { + None => self.tops.push(me), + Some(p) => self.walked[p].children.push(me), + } + if is_req { + self.requirements.push(me); + } + let kids: Vec = self.tree.children(n).to_vec(); + for (i, k) in kids.into_iter().enumerate() { + self.visit(k, i, Some(me), &address, holder, seen); + } + } + + fn path_of(&self, w: usize) -> String { + let walked = &self.walked[w]; + if let Some(r) = walked.requirement { + let r = &self.walked[r]; + let top = self.walked[r.top].node; + return format!( + "requirements/{}/{}.html", + package_dir(&self.package_of(top)), + page_stem(&r.address) + ); + } + let top = &self.walked[walked.top]; + let tn = self.tree.node(top.node); + let qualifier = format!("[{}.{}]", tn.type_name, tn.sub_type); + let typed = if top.id.ends_with(&qualifier) { + format!(".{}-{}", tn.type_name, tn.sub_type) + } else { + String::new() + }; + let page = format!( + "model/{}/{}{typed}.html", + package_dir(&self.package_of(top.node)), + page_stem(&tn.name) + ); + match walked.direct { + None => page, + Some(d) => format!("{page}#{}", self.walked[d].anchor), + } + } + + /// The package of the top-level node holding `n`, as every reference resolves in it. + fn package_of(&self, n: NodeId) -> String { + self.tree.effective_package(self.tree.top_level_of(n)) + } + + fn plain_of(&self, n: NodeId) -> String { + let pkg = self.package_of(n); + let name = &self.tree.node(n).name; + if pkg.is_empty() { + name.clone() + } else { + format!("{pkg}{PACKAGE_SEP}{name}") + } + } + + fn link(&self, w: usize) -> Value { + let walked = &self.walked[w]; + let node = self.tree.node(walked.node); + let label = if walked.requirement == Some(w) { + let title = str_attr(self.tree, walked.node, ATTR_TITLE); + if title.is_empty() { + node.name.clone() + } else { + title + } + } else if walked.top == w { + node.name.clone() + } else { + let top = &self.walked[walked.top]; + format!( + "{}{}", + self.tree.node(top.node).name, + &walked.id[top.id.len()..] + ) + }; + json!({ + "label": label, + "id": walked.id, + "path": walked.path, + "kind": format!("{}.{}", node.type_name, node.sub_type), + "unresolved": false, + }) + } + + fn link_to(&self, n: Option, text: &str) -> Value { + match n.and_then(|n| self.canonical.get(&n)) { + Some(&w) => self.link(w), + None => unresolved(text), + } + } + + /// The link a reference value lands on: the owner's row for the member its dotted tail + /// names, else the owner the loader bound. + fn ref_link(&self, owner: Option, value: &str) -> Value { + let Some(owner) = owner else { + return unresolved(value); + }; + let tail = split_child_tail(value).1; + let row = (!tail.is_empty()) + .then(|| { + self.by_plain + .get(&format!("{}{tail}", self.plain_of(owner))) + }) + .flatten(); + match row { + Some(&w) => self.link(w), + None => self.link_to(Some(owner), value), + } + } + + // ---- the build --------------------------------------------------------------------- + + fn run( + &self, + verify_in: Option<&Value>, + manifest: Option<&Value>, + routes_in: Option<&Value>, + ) -> Value { + let mut ledger = ledger_rows(verify_in); + let has_verify = ledger.is_some(); + let verify = verify_in.and_then(Value::as_object); + + // ── Requirements: claims first, since nodes and members list them. ── + let mut claims_on: HashMap> = HashMap::new(); + let mut req_links: HashMap> = HashMap::new(); + let mut req_targets: HashMap> = HashMap::new(); + for &r in &self.requirements { + let rn = self.walked[r].node; + let referrer_pkg = self.package_of(rn); + let mut links = Vec::new(); + let mut targets = Vec::new(); + for reference in string_list(self.tree.attr(rn, ATTR_IMPLEMENTED_BY)) { + let (owner, path) = split_member_ref(&reference); + let node = self.resolve_claim_target(owner, &referrer_pkg); + let member = match node { + Some(n) if !path.is_empty() => resolve_member(self.tree, n, &path), + other => other, + }; + let key = match node { + None => String::new(), + Some(n) if path.is_empty() => self.plain_of(n), + Some(n) => format!("{}{DOT}{}", self.plain_of(n), path.join(DOT)), + }; + let w = member.and_then(|_| self.by_plain.get(&key).copied()); + let Some(w) = w else { + links.push(req_link(&reference, false, unresolved(&reference))); + continue; + }; + links.push(req_link(&reference, true, self.link(w))); + targets.push(w); + let claim = json!({ + "requirement": self.link(r), + "member": if self.walked[w].top == w { String::new() } else { self.member_path(w) }, + "status": attr_text(self.tree, rn, ATTR_STATUS), + "level": level_of(self.tree, rn).map_or(Value::Null, Value::from), + }); + // The claim is on the top-level node and on every member down to the one it names. + let mut x = Some(w); + while let Some(i) = x { + claims_on.entry(i).or_default().push(claim.clone()); + x = self.walked[i].parent; + } + } + req_links.insert(r, links); + req_targets.insert(r, targets); + } + + // ── Files and routes. ── + let mut files_of: HashMap>> = HashMap::new(); + let manifest = manifest.and_then(Value::as_object); + if let Some(m) = manifest { + for (path, entry) in m { + let Some(entry) = entry.as_object() else { + continue; + }; + let Some(source) = string_of(entry, "sourceNode") else { + continue; + }; + let Some(&w) = self.by_plain.get(source) else { + continue; + }; + files_of + .entry(self.walked[w].top) + .or_default() + .entry( + string_of(entry, "generatedBy") + .unwrap_or_default() + .to_string(), + ) + .or_default() + .push(path.clone()); + } + } + let mut routes_of: HashMap> = HashMap::new(); + let routes_in = routes_in.and_then(Value::as_array); + if let Some(rs) = routes_in { + for r in rs { + let Some(r) = r.as_object() else { + continue; + }; + let (Some(node), Some(method), Some(path)) = ( + string_of(r, "node"), + string_of(r, "method"), + string_of(r, "path"), + ) else { + continue; + }; + let Some(&w) = self.by_plain.get(node) else { + continue; + }; + let method = js_upper(method); + routes_of.entry(self.walked[w].top).or_default().insert( + format!("{path}{NUL}{method}"), + json!({ "method": method, "path": path }), + ); + } + } + + // ── Advisories. ── + let mut advisories = Vec::new(); + let mut unclaimed_ids: HashSet = HashSet::new(); + let rows = verify + .filter(|_| has_verify) + .and_then(|v| v.get("requirements")) + .and_then(Value::as_object) + .and_then(|r| r.get("rows")) + .and_then(Value::as_array); + for d in rows.into_iter().flatten() { + let Some(d) = d.as_object() else { + continue; + }; + let node = string_of(d, "node").unwrap_or_default(); + let subject = if node.is_empty() { + Value::Null + } else { + match self.by_plain.get(node) { + Some(&w) => self.link(self.walked[w].top), + None => unresolved(node), + } + }; + let code = string_of(d, "code").unwrap_or_default(); + if code == CODE_OBJECT_UNCLAIMED + && let Some(id) = subject.get("id").and_then(Value::as_str) + { + unclaimed_ids.insert(id.to_string()); + } + advisories.push(json!({ + "code": code, + "path": string_of(d, "path").unwrap_or_default(), + "subject": subject, + "severity": string_of(d, "severity").unwrap_or_default(), + "source": string_of(d, "source").unwrap_or_default(), + "message": string_of(d, "message").unwrap_or_default(), + })); + } + + // ── Members and references. ── + let mut refs_from: HashMap> = HashMap::new(); + let mut nodes: Vec = Vec::new(); + let mut node_refs: HashMap> = HashMap::new(); + for &t in &self.tops { + let tn = self.walked[t].node; + let (attrs, attr_refs) = self.attrs_of(tn); + let ext = self.extends_link(tn); + let members: Vec = self.walked[t] + .children + .iter() + .map(|&c| self.member(c, &claims_on, &mut refs_from)) + .collect(); + let member_groups = group_members(members); + let mut all: Vec = Vec::new(); + if is_resolved(&ext) { + all.push(reference(EXTENDS, Value::Null, ext.clone())); + } + for (name, link) in attr_refs { + all.push(reference(&name, Value::Null, link)); + } + self.below(t, &refs_from, &mut all); + + let mut files = Vec::new(); + let mut file_count = 0usize; + if let Some(by_gen) = files_of.get(&t) { + for (generated_by, paths) in by_gen { + let mut paths = paths.clone(); + paths.sort(); + file_count += paths.len(); + files.push(json!({ "generatedBy": generated_by, "paths": paths })); + } + } + let routes: Vec = routes_of + .get(&t) + .map(|m| m.values().cloned().collect()) + .unwrap_or_default(); + let claims = claims_on.get(&t).cloned().unwrap_or_default(); + let walked = &self.walked[t]; + let node = self.tree.node(tn); + let counts = json!({ + "members": walked.children.len(), + "refs": all.len(), + "referencedBy": 0, + "claims": claims.len(), + "files": file_count, + "routes": routes.len(), + }); + nodes.push(json!({ + "id": walked.id, + "name": node.name, + "package": self.package_of(tn), + "type": node.type_name, + "subType": node.sub_type, + "order": walked.order, + "path": walked.path, + "title": str_attr(self.tree, tn, ATTR_TITLE), + "description": str_attr(self.tree, tn, ATTR_DESCRIPTION), + "summary": str_attr(self.tree, tn, ATTR_SUMMARY), + "abstract": is_abstract(self.tree, tn), + "extends": ext, + "attrs": attrs, + "memberGroups": member_groups, + "refs": all.clone(), + "referencedBy": [], + "claims": claims, + "files": files, + "routes": routes, + "unclaimed": unclaimed_ids.contains(&walked.id), + "counts": counts, + })); + node_refs.insert(t, all); + } + + // referencedBy: every reference into a top-level node (or a member of it) from another one. + let mut incoming: HashMap> = HashMap::new(); + for &t in &self.tops { + for r in node_refs.get(&t).into_iter().flatten() { + let target = &r["target"]; + let target_id = target["id"].as_str().unwrap_or_default(); + let Some(&tw) = self.by_id.get(target_id) else { + continue; + }; + if self.walked[tw].top == t { + continue; + } + let via = &r["via"]; + let attr = r["attr"].as_str().unwrap_or_default(); + let via_id = via.get("id").and_then(Value::as_str).unwrap_or_default(); + let key = [self.walked[t].id.as_str(), attr, via_id, target_id].join(NUL); + incoming + .entry(self.walked[self.walked[tw].top].id.clone()) + .or_default() + .insert( + key, + json!({ "attr": attr, "from": self.link(t), "via": via, "target": target }), + ); + } + } + for n in &mut nodes { + let id = n["id"].as_str().unwrap_or_default().to_string(); + if let Some(by) = incoming.get(&id) { + let by: Vec = by.values().cloned().collect(); + n["counts"]["referencedBy"] = Value::from(by.len()); + n["referencedBy"] = Value::Array(by); + } + } + nodes.sort_by(|a, c| id_of(a).cmp(id_of(c))); + + // ── The requirement list, flat, in document order. ── + let mut req_children: HashMap> = HashMap::new(); + for &r in &self.requirements { + if let Some(p) = self.req_parent(r) { + req_children.entry(p).or_default().push(r); + } + } + let mut reqs: Vec = Vec::new(); + for &r in &self.requirements { + let rw = &self.walked[r]; + let rn = rw.node; + let pkg = self.package_of(rn); + let qualified_path = qualify(&pkg, &rw.address); + let row = ledger + .as_mut() + .and_then(|l| l.get_mut(&qualified_path)) + .and_then(VecDeque::pop_front); + let mut chain = Vec::new(); + let mut p = self.req_parent(r); + while let Some(x) = p { + chain.insert(0, x); + p = self.req_parent(x); + } + let mut sub = Vec::new(); + subtree(r, &req_children, &mut sub); + let linked: Vec = sub + .iter() + .copied() + .filter(|&x| { + let xn = self.walked[x].node; + let level = level_of(self.tree, xn); + level.unwrap_or(0) >= LEVEL_OBJECT + || (level.is_none() + && !string_list(self.tree.attr(xn, ATTR_IMPLEMENTED_BY)).is_empty()) + }) + .collect(); + let counted = if linked.is_empty() { vec![r] } else { linked }; + let statuses: Vec = counted + .iter() + .map(|&x| attr_text(self.tree, self.walked[x].node, ATTR_STATUS)) + .filter(|s| !s.is_empty()) + .collect(); + let mut target_tops: BTreeMap = BTreeMap::new(); + for &x in &sub { + for &w in req_targets.get(&x).into_iter().flatten() { + let top = self.walked[w].top; + target_tops + .entry(self.walked[top].id.clone()) + .or_insert(top); + } + } + let children = req_children.get(&r).cloned().unwrap_or_default(); + let superseded_by = match &row { + Some(row) if row.has_sup => { + let target = (!row.sup_target.is_empty()) + .then(|| { + self.requirements.iter().copied().find(|&x| { + let xw = &self.walked[x]; + qualify(&self.package_of(xw.node), &xw.address) == row.sup_target + }) + }) + .flatten(); + req_link( + &row.sup_ref, + row.sup_resolves, + target.map_or_else(|| unresolved(&row.sup_ref), |t| self.link(t)), + ) + } + _ => Value::Null, + }; + let link = self.link(r); + reqs.push(json!({ + "id": rw.id, + "name": self.tree.node(rn).name, + "label": link["label"], + "path": rw.path, + "address": rw.address, + "package": pkg, + "qualifiedPath": qualified_path, + "subType": self.tree.node(rn).sub_type, + "level": level_of(self.tree, rn).map_or(Value::Null, Value::from), + "status": attr_text(self.tree, rn, ATTR_STATUS), + "disposition": attr_text(self.tree, rn, ATTR_DISPOSITION), + "statement": str_attr(self.tree, rn, ATTR_STATEMENT), + "counterexample": str_attr(self.tree, rn, ATTR_COUNTEREXAMPLE), + "title": str_attr(self.tree, rn, ATTR_TITLE), + "description": str_attr(self.tree, rn, ATTR_DESCRIPTION), + "trackedBy": string_list(self.tree.attr(rn, ATTR_TRACKED_BY)), + "depth": chain.len(), + "parent": chain.last().map_or(Value::Null, |&p| self.link(p)), + "breadcrumbs": chain.iter().map(|&x| self.link(x)).collect::>(), + "children": children.iter().map(|&x| self.link(x)).collect::>(), + "implementedBy": req_links.get(&r).cloned().unwrap_or_default(), + "supersededBy": superseded_by, + "inLedger": row.is_some(), + "verdict": row.as_ref().map_or("", |r| r.verdict.as_str()), + "digest": row.as_ref().map_or("", |r| r.digest.as_str()), + "diagnostics": row.as_ref().map_or_else(Vec::new, |r| r.diagnostics.clone()), + "rollup": status_counts(&statuses), + "rollupTotal": statuses.len(), + "belowCount": sub.len() - 1, + "childCount": children.len(), + "targets": target_tops.values().map(|&w| self.link(w)).collect::>(), + "targetCount": target_tops.len(), + })); + } + + // ── Packages, counts, slices. ── + let pkg_names: BTreeSet<&str> = nodes.iter().map(package_of_view).collect(); + let mut packages = Vec::new(); + for name in &pkg_names { + let mut groups: BTreeMap = BTreeMap::new(); + let mut count = 0usize; + for n in nodes.iter().filter(|n| package_of_view(n) == *name) { + count += 1; + let type_name = n["type"].as_str().unwrap_or_default(); + let sub_type = n["subType"].as_str().unwrap_or_default(); + let g = groups + .entry(format!("{type_name}.{sub_type}")) + .or_insert_with(|| { + json!({ "type": type_name, "subType": sub_type, "count": 0, "nodes": [] }) + }); + g["count"] = Value::from(g["count"].as_u64().unwrap_or(0) + 1); + if let Some(&w) = self.by_id.get(id_of(n)) + && let Some(arr) = g["nodes"].as_array_mut() + { + arr.push(self.link(w)); + } + } + packages.push(json!({ + "name": name, + "count": count, + "groups": groups.into_values().collect::>(), + })); + } + + let vc = verify + .and_then(|v| v.get("requirementCounts")) + .and_then(Value::as_object); + let mut all_files: HashSet<&str> = HashSet::new(); + let mut route_count = 0usize; + for n in &nodes { + for g in n["files"].as_array().into_iter().flatten() { + for p in g["paths"].as_array().into_iter().flatten() { + all_files.insert(p.as_str().unwrap_or_default()); + } + } + route_count += n["routes"].as_array().map_or(0, Vec::len); + } + let mut functional = 0usize; + let mut architectural = 0usize; + let mut claim_count = 0usize; + let mut req_statuses = Vec::new(); + for r in &reqs { + match r["subType"].as_str() { + Some(SUBTYPE_FUNCTIONAL) => functional += 1, + Some(SUBTYPE_ARCHITECTURAL) => architectural += 1, + _ => {} + } + req_statuses.push(r["status"].as_str().unwrap_or_default().to_string()); + claim_count += r["implementedBy"] + .as_array() + .into_iter() + .flatten() + .filter(|l| l["resolves"] == Value::Bool(true)) + .count(); + } + let num = |key: &str| { + vc.and_then(|o| o.get(key)) + .filter(|v| v.is_number()) + .cloned() + .unwrap_or(Value::from(0)) + }; + let counts = json!({ + "nodes": nodes.len(), + "packages": packages.len(), + "requirements": reqs.len(), + "functional": functional, + "architectural": architectural, + "byStatus": status_counts(&req_statuses), + "claims": claim_count, + "files": all_files.len(), + "routes": route_count, + "undecided": num("undecided"), + "coverageMeasured": vc.and_then(|o| o.get("entitiesTotal")).is_some_and(Value::is_number), + "entitiesClaimed": num("entitiesClaimed"), + "entitiesTotal": num("entitiesTotal"), + }); + let slices = self.slices(&nodes, &reqs); + json!({ + "format": FORMAT, + "sources": { + "requirements": has_verify, + "files": manifest.is_some(), + "routes": routes_in.is_some(), + }, + "counts": counts, + "packages": packages, + "nodes": nodes, + "requirements": reqs, + "advisories": advisories, + "slices": slices, + }) + } + + fn slices(&self, nodes: &[Value], reqs: &[Value]) -> Vec { + let mut slices = Vec::new(); + let pkgs: BTreeSet<&str> = nodes.iter().map(package_of_view).collect(); + for pkg in pkgs { + let ids: BTreeSet = nodes + .iter() + .filter(|n| package_of_view(n) == pkg) + .map(|n| id_of(n).to_string()) + .collect(); + slices.push(slice("package", pkg, ids)); + } + // A requirement with requirements below it: the subtree, each node it claims, and the + // top-level node holding a claimed member. + let req_by_id: HashMap<&str, &Value> = reqs.iter().map(|r| (id_of(r), r)).collect(); + for r in reqs { + if r["childCount"].as_u64().unwrap_or(0) == 0 { + continue; + } + let mut ids = BTreeSet::new(); + self.slice_visit(r, &req_by_id, &mut ids); + slices.push(slice("requirement", id_of(r), ids)); + } + // A template: itself and what its own attributes reference. + for n in nodes { + if n["type"].as_str() != Some(TYPE_TEMPLATE) { + continue; + } + let mut ids = BTreeSet::new(); + ids.insert(id_of(n).to_string()); + for r in n["refs"].as_array().into_iter().flatten() { + if !r["via"].is_null() { + continue; + } + let tid = r["target"]["id"].as_str().unwrap_or_default(); + ids.insert(match self.by_id.get(tid) { + Some(&w) => self.walked[self.walked[w].top].id.clone(), + None => tid.to_string(), + }); + } + slices.push(slice("prompt", id_of(n), ids)); + } + slices.sort_by(|a, c| id_of(a).cmp(id_of(c))); + slices + } + + fn slice_visit( + &self, + x: &Value, + req_by_id: &HashMap<&str, &Value>, + ids: &mut BTreeSet, + ) { + ids.insert(id_of(x).to_string()); + for l in x["implementedBy"].as_array().into_iter().flatten() { + if l["resolves"] != Value::Bool(true) { + continue; + } + let tid = l["target"]["id"].as_str().unwrap_or_default(); + ids.insert(tid.to_string()); + if let Some(&w) = self.by_id.get(tid) { + ids.insert(self.walked[self.walked[w].top].id.clone()); + } + } + for c in x["children"].as_array().into_iter().flatten() { + if let Some(child) = req_by_id.get(id_of(c)) { + self.slice_visit(child, req_by_id, ids); + } + } + } + + fn req_parent(&self, r: usize) -> Option { + self.walked[r] + .parent + .and_then(|p| self.walked[p].requirement) + } + + fn below(&self, w: usize, refs_from: &HashMap>, all: &mut Vec) { + for &c in &self.walked[w].children { + all.extend(refs_from.get(&c).into_iter().flatten().cloned()); + self.below(c, refs_from, all); + } + } + + fn member( + &self, + w: usize, + claims_on: &HashMap>, + refs_from: &mut HashMap>, + ) -> Value { + let n = self.walked[w].node; + let (attrs, attr_refs) = self.attrs_of(n); + let ext = self.extends_link(n); + let mut own = Vec::new(); + if is_resolved(&ext) { + own.push(reference(EXTENDS, self.link(w), ext.clone())); + } + for (name, link) in attr_refs { + own.push(reference(&name, self.link(w), link)); + } + refs_from.insert(w, own.clone()); + let walked = &self.walked[w]; + let node = self.tree.node(n); + let declared_on = walked.declared_on.map_or(Value::Null, |d| { + self.link_to(Some(d), &self.tree.node(d).name) + }); + let children: Vec = walked.children.clone(); + let members: Vec = children + .into_iter() + .map(|c| self.member(c, claims_on, refs_from)) + .collect(); + json!({ + "id": walked.id, + "name": node.name, + "type": node.type_name, + "subType": node.sub_type, + "order": walked.order, + "anchor": walked.anchor, + "path": walked.path, + "abstract": is_abstract(self.tree, n), + "isArray": node.type_name == TYPE_FIELD && is_array(self.tree, n), + "extends": ext, + "declaredOn": declared_on, + "attrs": attrs, + "refs": own, + "claims": claims_on.get(&w).cloned().unwrap_or_default(), + "memberGroups": group_members(members), + }) + } + + fn extends_link(&self, n: NodeId) -> Value { + let node = self.tree.node(n); + let written = node + .authored_super_ref + .as_deref() + .or(node.super_ref.as_deref()); + if node.super_node.is_none() && written.is_none() { + return Value::Null; + } + self.link_to(node.super_node, written.unwrap_or_default()) + } + + /// A node's effective attributes, by name, each value linked where the loader resolved it; + /// and the links that resolved, in order, as `(attr, link)`. + fn attrs_of(&self, n: NodeId) -> (Vec, Vec<(String, Value)>) { + let type_name = self.tree.node(n).type_name.as_str(); + let effective = self.tree.attrs(n); + let by_name: BTreeMap<&String, &Value> = effective + .iter() + // `isAbstract` and `isArray` are native flags in the view, not attributes. + .filter(|(k, _)| k.as_str() != ATTR_IS_ABSTRACT && k.as_str() != ATTR_IS_ARRAY) + .collect(); + let mut attrs = Vec::new(); + let mut refs = Vec::new(); + for (name, raw) in by_name { + let value = canonical_value(normalize(raw.clone())); + let is_ref = is_ref_bearing_attr(type_name, name); + let resolved = if is_ref { + self.declaring_targets(n, name) + } else { + Vec::new() + }; + let mut values = Vec::new(); + match &value { + Value::String(text) => { + let link = if is_ref { + self.ref_link(resolved.first().copied().flatten(), text) + } else { + Value::Null + }; + if is_resolved(&link) { + refs.push((name.clone(), link.clone())); + } + values.push(attr_value(text, link)); + } + Value::Array(items) if items.iter().all(Value::is_string) => { + for (i, item) in items.iter().enumerate() { + let item = item.as_str().unwrap_or_default(); + let link = if is_ref { + self.ref_link(resolved.get(i).copied().flatten(), item) + } else { + Value::Null + }; + if is_resolved(&link) { + refs.push((name.clone(), link.clone())); + } + values.push(attr_value(item, link)); + } + } + other => values.push(attr_value(&to_js_compact(other), Value::Null)), + } + attrs.push(json!({ "name": name, "value": value, "values": values })); + } + (attrs, refs) + } + + /// What the loader bound for `name` on the layer that declares it (own, else the nearest + /// `extends` ancestor). + fn declaring_targets(&self, n: NodeId, name: &str) -> Vec> { + let mut seen = HashSet::new(); + let mut cur = Some(n); + while let Some(x) = cur { + if !seen.insert(x) { + break; + } + // ADR-0039: own — locating the layer that declares the attr, walking the super chain. + if self.tree.own_attr(x, name).is_some() { + return reference_targets(self.tree, &self.objects, x, name); + } + cur = self.tree.node(x).super_node; + } + Vec::new() + } + + /// Resolve the owner of an `@implementedBy` reference: objects first, as every reference + /// resolves; then root-level nodes that are neither objects nor requirements (a + /// `template.prompt` and its siblings). An ambiguous bare name binds nothing. + fn resolve_claim_target(&self, owner: &str, referrer_pkg: &str) -> Option { + if let Some(o) = self.objects.resolve(owner, referrer_pkg) { + return Some(o); + } + // ADR-0039 own: the root's top-level nodes are its declared children; a root extends nothing. + let candidates: Vec = self + .tree + .own_children(self.root) + .iter() + .copied() + .filter(|&c| { + let t = &self.tree.node(c).type_name; + t != TYPE_OBJECT && t != TYPE_REQUIREMENT + }) + .collect(); + let key = |c: NodeId| self.tree.resolution_key(c); + if owner.contains(PACKAGE_SEP) { + return candidates.into_iter().find(|&c| key(c) == owner); + } + let one = |matches: Vec| (matches.len() == 1).then(|| matches[0]); + if !referrer_pkg.is_empty() { + let local = format!("{referrer_pkg}{PACKAGE_SEP}{owner}"); + if let Some(c) = one(candidates + .iter() + .copied() + .filter(|&c| key(c) == local) + .collect()) + { + return Some(c); + } + } + one(candidates + .into_iter() + .filter(|&c| self.tree.node(c).name == owner && key(c) == owner) + .collect()) + } + + /// A member's id after its top-level node's. + fn member_path(&self, w: usize) -> String { + let walked = &self.walked[w]; + let rest = &walked.id[self.walked[walked.top].id.len()..]; + rest.strip_prefix(DOT).unwrap_or(rest).to_string() + } +} + +// ---- helpers ------------------------------------------------------------------------------- + +/// Split an `@implementedBy` reference into its owner and its dotted member path, at the first +/// `.` after the last `::`. +fn split_member_ref(r: &str) -> (&str, Vec) { + let from = r.rfind(PACKAGE_SEP).map_or(0, |i| i + PACKAGE_SEP.len()); + match r[from..].find('.') { + None => (r, Vec::new()), + Some(dot) => { + let (owner, rest) = r.split_at(from + dot); + (owner, rest[1..].split('.').map(str::to_string).collect()) + } + } +} + +/// Walk dotted member segments by child name from a node, through its effective children. +fn resolve_member(tree: &Tree, n: NodeId, path: &[String]) -> Option { + let mut cur = n; + for seg in path { + cur = tree + .children(cur) + .iter() + .copied() + .find(|&c| tree.node(c).name == *seg)?; + } + Some(cur) +} + +fn qualified(id: &str, tree: &Tree, n: NodeId) -> String { + let node = tree.node(n); + format!("{id}[{}.{}]", node.type_name, node.sub_type) +} + +/// `m-` for a field, `m--` for anything else, `m--` with no name. +fn member_anchor(tree: &Tree, n: NodeId, name: &str, order: usize) -> String { + let t = &tree.node(n).type_name; + if name.is_empty() { + format!("m-{t}-{order}") + } else if t == TYPE_FIELD { + format!("m-{name}") + } else { + format!("m-{t}-{name}") + } +} + +fn package_dir(pkg: &str) -> String { + if pkg.is_empty() { + "-root".to_string() + } else { + pkg.split(PACKAGE_SEP).collect::>().join("/") + } +} + +fn page_stem(name: &str) -> String { + if name.to_lowercase() == "index" { + format!("{name}.node") + } else { + name.to_string() + } +} + +fn qualify(pkg: &str, address: &str) -> String { + if pkg.is_empty() { + address.to_string() + } else { + format!("{pkg}{PACKAGE_SEP}{address}") + } +} + +/// `@isAbstract` is a declaration-layer marker, never inherited. +fn is_abstract(tree: &Tree, n: NodeId) -> bool { + // ADR-0039: own — @isAbstract is a declaration-layer marker, never inherited. + tree.node(n).is_abstract + || tree.own_attr(n, ATTR_IS_ABSTRACT).map(|a| &a.value) == Some(&Value::Bool(true)) +} + +fn is_array(tree: &Tree, n: NodeId) -> bool { + tree.resolved_is_array(n) || tree.attr(n, ATTR_IS_ARRAY) == Some(&Value::Bool(true)) +} + +/// A string attribute's effective value, `""` when it is absent or not a string. +fn str_attr(tree: &Tree, n: NodeId, name: &str) -> String { + match tree.attr(n, name) { + Some(Value::String(s)) => s.clone(), + _ => String::new(), + } +} + +/// An attribute's effective value as text (a number as JavaScript prints it), `""` when absent. +fn attr_text(tree: &Tree, n: NodeId, name: &str) -> String { + match tree.attr(n, name) { + None | Some(Value::Null) => String::new(), + Some(v) => crate::json::js_display(v), + } +} + +/// A requirement's `@level`: a number (saturated to 32 bits) or a numeric string. +fn level_of(tree: &Tree, n: NodeId) -> Option { + let saturate = |v: i64| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)); + match tree.attr(n, ATTR_LEVEL)? { + Value::Number(num) => num + .as_i64() + .or_else(|| { + #[allow(clippy::cast_possible_truncation)] + num.as_f64().map(|f| f.trunc() as i64) + }) + .map(saturate), + Value::String(s) => s.trim().parse::().ok().map(saturate), + _ => None, + } +} + +/// A list attribute: a list of strings, or one comma-separated string. +fn string_list(v: Option<&Value>) -> Vec { + match v { + Some(Value::Array(items)) => items + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect(), + Some(Value::String(s)) => s + .split(',') + .map(str::trim) + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect(), + _ => Vec::new(), + } +} + +/// JavaScript's `toUpperCase`, locale-independent. +fn js_upper(s: &str) -> String { + s.to_uppercase() +} + +fn unresolved(text: &str) -> Value { + json!({ "label": text, "id": "", "path": "", "kind": "", "unresolved": true }) +} + +fn is_resolved(link: &Value) -> bool { + link.get("unresolved") == Some(&Value::Bool(false)) +} + +fn req_link(r: &str, resolves: bool, target: Value) -> Value { + json!({ "ref": r, "resolves": resolves, "target": target }) +} + +fn reference(attr: &str, via: Value, target: Value) -> Value { + json!({ "attr": attr, "via": via, "target": target }) +} + +fn attr_value(text: &str, link: Value) -> Value { + json!({ "text": text, "link": link }) +} + +fn id_of(v: &Value) -> &str { + v["id"].as_str().unwrap_or_default() +} + +fn package_of_view(v: &Value) -> &str { + v["package"].as_str().unwrap_or_default() +} + +fn string_of<'a>(o: &'a Map, key: &str) -> Option<&'a str> { + o.get(key).and_then(Value::as_str) +} + +fn group_members(members: Vec) -> Vec { + let mut order: Vec = Vec::new(); + let mut groups: HashMap> = HashMap::new(); + for m in members { + let t = m["type"].as_str().unwrap_or_default().to_string(); + if !groups.contains_key(&t) { + order.push(t.clone()); + } + groups.entry(t).or_default().push(m); + } + order + .into_iter() + .map(|t| { + let members = groups.remove(&t).unwrap_or_default(); + json!({ "type": t, "count": members.len(), "members": members }) + }) + .collect() +} + +fn status_counts(statuses: &[String]) -> Vec { + STATUSES + .iter() + .map(|s| json!({ "status": s, "count": statuses.iter().filter(|x| x == s).count() })) + .collect() +} + +fn slice(kind: &str, anchor: &str, ids: BTreeSet) -> Value { + json!({ + "id": format!("{kind}:{anchor}"), + "kind": kind, + "anchor": anchor, + "nodes": ids.into_iter().collect::>(), + }) +} + +fn subtree(r: usize, req_children: &HashMap>, out: &mut Vec) { + out.push(r); + for &c in req_children.get(&r).into_iter().flatten() { + subtree(c, req_children, out); + } +} + +/// The verify payload's requirement ledger, by qualified path (a path may have more than one +/// row, used in document order); `None` when the payload has no ledger. +fn ledger_rows(verify: Option<&Value>) -> Option>> { + let ledger = verify?.as_object()?.get("requirementLedger")?.as_array()?; + let mut out: HashMap> = HashMap::new(); + for raw in ledger { + let Some(raw) = raw.as_object() else { + continue; + }; + let Some(qp) = string_of(raw, "qualifiedPath") else { + continue; + }; + let diagnostics = raw + .get("diagnostics") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_object) + .map(|d| { + let f = |k: &str| string_of(d, k).unwrap_or_default(); + json!({ + "code": f("code"), + "severity": f("severity"), + "source": f("source"), + "message": f("message"), + }) + }) + .collect(); + let sup = raw + .get("supersededBy") + .and_then(Value::as_object) + .filter(|s| string_of(s, "ref").is_some()); + let sup_str = |k: &str| { + sup.and_then(|s| string_of(s, k)) + .unwrap_or_default() + .to_string() + }; + out.entry(qp.to_string()).or_default().push_back(Ledger { + digest: string_of(raw, "digest").unwrap_or_default().to_string(), + verdict: string_of(raw, "verdict").unwrap_or_default().to_string(), + diagnostics, + sup_ref: sup_str("ref"), + sup_resolves: sup.and_then(|s| s.get("resolves")) == Some(&Value::Bool(true)), + sup_target: sup_str("target"), + has_sup: sup.is_some(), + }); + } + Some(out) +} + +/// A value with every object's keys in code-unit order, as the canonical serializer writes them. +fn canonical_value(v: Value) -> Value { + match v { + Value::Array(items) => Value::Array(items.into_iter().map(canonical_value).collect()), + Value::Object(map) => { + let sorted: BTreeMap = map.into_iter().collect(); + Value::Object( + sorted + .into_iter() + .map(|(k, v)| (k, canonical_value(v))) + .collect(), + ) + } + other => other, + } +} diff --git a/server/rust/metaobjects/src/json.rs b/server/rust/metaobjects/src/json.rs index cc09e92de5..a8045d7904 100644 --- a/server/rust/metaobjects/src/json.rs +++ b/server/rust/metaobjects/src/json.rs @@ -14,11 +14,27 @@ use serde_json::{Map, Number, Value}; /// Serialize `value` as `JSON.stringify(value, null, 2)` would. pub fn to_js_pretty(value: &Value) -> String { let mut out = String::new(); - write_value(&mut out, value, 0); + write_value(&mut out, value, Some(0)); out } -fn write_value(out: &mut String, value: &Value, depth: usize) { +/// Serialize `value` as `JSON.stringify(value)` would: no whitespace. +pub fn to_js_compact(value: &Value) -> String { + let mut out = String::new(); + write_value(&mut out, value, None); + out +} + +/// A string as a JSON string literal, as `JSON.stringify(s)` writes it. +pub fn js_quote(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + write_string(&mut out, s); + out +} + +/// `depth` is the indentation level of a pretty write, `None` for a compact one. +fn write_value(out: &mut String, value: &Value, depth: Option) { + let inner = depth.map(|d| d + 1); match value { Value::Null => out.push_str("null"), Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }), @@ -34,8 +50,8 @@ fn write_value(out: &mut String, value: &Value, depth: usize) { if i > 0 { out.push(','); } - newline(out, depth + 1); - write_value(out, item, depth + 1); + newline(out, inner); + write_value(out, item, inner); } newline(out, depth); out.push(']'); @@ -50,10 +66,10 @@ fn write_value(out: &mut String, value: &Value, depth: usize) { if i > 0 { out.push(','); } - newline(out, depth + 1); + newline(out, inner); write_string(out, key); - out.push_str(": "); - write_value(out, item, depth + 1); + out.push_str(if depth.is_some() { ": " } else { ":" }); + write_value(out, item, inner); } newline(out, depth); out.push('}'); @@ -61,7 +77,10 @@ fn write_value(out: &mut String, value: &Value, depth: usize) { } } -fn newline(out: &mut String, depth: usize) { +fn newline(out: &mut String, depth: Option) { + let Some(depth) = depth else { + return; + }; out.push('\n'); for _ in 0..depth { out.push_str(" "); @@ -205,6 +224,14 @@ mod tests { ); } + #[test] + fn compact_has_no_whitespace() { + let v: Value = serde_json::from_str(r#"{"b":[1.0,{"2":true}],"1":"x"}"#).unwrap(); + assert_eq!(to_js_compact(&v), r#"{"1":"x","b":[1,{"2":true}]}"#); + assert_eq!(to_js_compact(&json!([])), "[]"); + assert_eq!(js_quote("a\u{1}<>&"), "\"a\\u0001<>&\""); + } + #[test] fn control_characters_escape_like_javascript() { assert_eq!(to_js_pretty(&json!("a\"\u{1}\n")), "\"a\\\"\\u0001\\n\""); diff --git a/server/rust/metaobjects/src/lib.rs b/server/rust/metaobjects/src/lib.rs index 623428e964..55b797339c 100644 --- a/server/rust/metaobjects/src/lib.rs +++ b/server/rust/metaobjects/src/lib.rs @@ -8,11 +8,13 @@ pub mod collection; pub mod config; +pub mod docs_view; pub mod errors; pub mod json; pub mod library; pub mod loader; pub mod manifest; +pub mod meta_endpoint; pub mod metamodel_docs; pub mod naming; pub mod node; diff --git a/server/rust/metaobjects/src/loader.rs b/server/rust/metaobjects/src/loader.rs index 72b5b49f45..8d5943aa95 100644 --- a/server/rust/metaobjects/src/loader.rs +++ b/server/rust/metaobjects/src/loader.rs @@ -969,7 +969,7 @@ fn resolve_references(tree: &mut Tree, root: NodeId, top: &TopLevel) { .map(|(k, _)| k.clone()) .collect(); for name in names { - let ref_pkg = referrer_package(tree, top, id, &name, &decl_pkg); + let ref_pkg = referrer_package(tree, &top.objects, id, &name, &decl_pkg); resolve_attr(tree, top, id, &name, &ref_pkg, &decl_pkg); } } @@ -996,14 +996,20 @@ fn resolve_one( /// dimension's `@of` resolves in the package of the entity its `@via` walk reaches; /// a report's `@spine` in the package of its `@from`; everything else in the package /// of the top-level node that declares it. -fn referrer_package(tree: &Tree, top: &TopLevel, id: NodeId, attr: &str, decl_pkg: &str) -> String { +fn referrer_package( + tree: &Tree, + objects: &ObjectIndex, + id: NodeId, + attr: &str, + decl_pkg: &str, +) -> String { let node = tree.node(id); if node.type_name == "dimension" && attr == "of" { // ADR-0039: resolving: the @via that governs this @of may be inherited. if let (Some(Value::String(via)), Some(declaring)) = (tree.attr(id, "via"), node.parent) && !via.is_empty() { - return match dimension_via_terminal(tree, top, declaring, via) { + return match dimension_via_terminal(tree, objects, declaring, via) { Some(t) => tree.effective_package(t), None => decl_pkg.to_string(), }; @@ -1013,7 +1019,7 @@ fn referrer_package(tree: &Tree, top: &TopLevel, id: NodeId, attr: &str, decl_pk // ADR-0039: resolving: @from may be inherited. if let Some(Value::String(from)) = tree.attr(id, "from") && !from.is_empty() - && let Some(from_node) = top.objects.resolve(from, decl_pkg) + && let Some(from_node) = objects.resolve(from, decl_pkg) { return tree.effective_package(from_node); } @@ -1026,7 +1032,7 @@ fn referrer_package(tree: &Tree, top: &TopLevel, id: NodeId, attr: &str, decl_pk /// when the walk fails (the reporting pass reports why). fn dimension_via_terminal( tree: &Tree, - top: &TopLevel, + objects: &ObjectIndex, declaring: NodeId, via: &str, ) -> Option { @@ -1037,11 +1043,46 @@ fn dimension_via_terminal( for hop_name in parts { any = true; let (hop, is_ref) = find_hop(tree, current, hop_name)?; - current = top.objects.hop_target(tree, hop, is_ref)?; + current = objects.hop_target(tree, hop, is_ref)?; } any.then_some(current) } +/// The object each value of the reference attribute `attr` that `id` declares itself +/// resolves to, as the loader resolved it (ADR-0059 R3-R5): one entry for a string value, +/// one per item for a list of strings, none for anything else. An entry is `None` for a +/// value that resolves to no object. `objects` is the loaded root's [`ObjectIndex`]. +/// +/// The loader rewrites a resolved value to its canonical spelling and keeps no node for it, +/// so a reader that needs the node (the docs view's links) asks here, in the package the +/// loader resolved that attribute in. +pub fn reference_targets( + tree: &Tree, + objects: &ObjectIndex, + id: NodeId, + attr: &str, +) -> Vec> { + // ADR-0039: own — the layer that declares the attribute is the one the loader resolved. + let Some(a) = tree.own_attr(id, attr) else { + return Vec::new(); + }; + let decl_pkg = tree.effective_package(tree.top_level_of(id)); + let pkg = referrer_package(tree, objects, id, attr, &decl_pkg); + let one = |s: &str| { + (!s.is_empty()) + .then(|| objects.resolve(split_child_tail(s).0, &pkg)) + .flatten() + }; + match &a.value { + Value::String(s) => vec![one(s)], + Value::Array(items) if items.iter().all(Value::is_string) => items + .iter() + .map(|v| one(v.as_str().unwrap_or_default())) + .collect(), + _ => Vec::new(), + } +} + fn resolve_attr( tree: &mut Tree, top: &TopLevel, diff --git a/server/rust/metaobjects/src/meta_endpoint.rs b/server/rust/metaobjects/src/meta_endpoint.rs new file mode 100644 index 0000000000..59df283f0d --- /dev/null +++ b/server/rust/metaobjects/src/meta_endpoint.rs @@ -0,0 +1,113 @@ +//! The running application's metadata routes, framework-free: `GET /_meta` (the effective +//! canonical model) and `GET /_meta/docs` (the docs view the explorer reads), as +//! `docs/features/metadata-api.md` specifies them. The same symbols as TypeScript's +//! `@metaobjectsdev/runtime-ts` and Java's `MetaEndpoint`. +//! +//! Both routes are opt-in: nothing here mounts anything. The host mounts them on its own web +//! framework, behind the guard the rest of its API uses, so this crate takes no web dependency. +//! With axum, for example: +//! +//! ```text +//! // root: the model this app loaded. Built once: the model does not change after load. +//! let docs = Arc::new(meta_endpoint::docs(&tree, root, None)); +//! let route = format!("/api{}", meta_endpoint::META_DOCS_ROUTE_PATH); +//! app.route(&route, get(move |headers: HeaderMap| async move { +//! let tag = headers.get(IF_NONE_MATCH).and_then(|v| v.to_str().ok()); +//! let common = [(ETAG, docs.etag.clone()), (CACHE_CONTROL, "no-cache".into())]; +//! if docs.matches(tag) { +//! (StatusCode::NOT_MODIFIED, common).into_response() +//! } else { +//! (common, [(CONTENT_TYPE, "application/json")], docs.body.clone()).into_response() +//! } +//! })); +//! ``` + +use serde_json::Value; + +use crate::docs_view; +use crate::node::{NodeId, Tree}; +use crate::serializer::canonical_serialize_effective; + +/// Where the model is served, under the application's API prefix. +pub const META_ROUTE_PATH: &str = "/_meta"; +/// Where the docs view is served, beside the model. +pub const META_DOCS_ROUTE_PATH: &str = "/_meta/docs"; + +/// The `/_meta` body: the model as the effective canonical serializer writes it. +pub fn meta_json(tree: &Tree, root: NodeId) -> String { + canonical_serialize_effective(tree, root) +} + +/// The `/_meta/docs` body: the docs view of the loaded model, with the routes the application +/// mounts when it names them (`[{ node, method, path }]`, `node` a resolution key). It carries no +/// requirement ledger and no generated files: those are build facts, which the docs-site +/// generator reads. +pub fn meta_docs_json(tree: &Tree, root: NodeId, routes: Option<&Value>) -> String { + docs_view::serialize(&docs_view::build(tree, root, None, None, routes)) +} + +/// The docs view body, built once, with its ETag. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Docs { + pub body: String, + pub etag: String, +} + +impl Docs { + /// Whether a request's `If-None-Match` names this body, so the answer is a 304. + pub fn matches(&self, if_none_match: Option<&str>) -> bool { + etag_matches(if_none_match, &self.etag) + } +} + +/// The docs view of the loaded model and its ETag ([`meta_docs_json`]). +pub fn docs(tree: &Tree, root: NodeId, routes: Option<&Value>) -> Docs { + let body = meta_docs_json(tree, root, routes); + let etag = meta_docs_etag(&body); + Docs { body, etag } +} + +/// A strong ETag for a docs view body: its length and the 32-bit FNV-1a hash of its UTF-16 code +/// units, quoted, the value TypeScript's mount sends. A client compares it and never parses it. +pub fn meta_docs_etag(body: &str) -> String { + let mut h: u32 = 0x811c_9dc5; + let mut units: usize = 0; + for c in body.encode_utf16() { + h ^= u32::from(c); + h = h.wrapping_mul(0x0100_0193); + units += 1; + } + format!("\"{units:x}-{h:08x}\"") +} + +/// Whether an `If-None-Match` header value names `etag` (or is `*`). +pub fn etag_matches(if_none_match: Option<&str>, etag: &str) -> bool { + if_none_match.is_some_and(|v| { + v.split(',').any(|t| { + let t = t.trim(); + let t = t.strip_prefix("W/").unwrap_or(t); + t == "*" || t == etag + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_etag_counts_utf16_units() { + // metaDocsEtag("é😀") in TypeScript: three UTF-16 units. + assert_eq!(meta_docs_etag("é\u{1F600}"), "\"3-44cc4da1\""); + } + + #[test] + fn if_none_match_lists_weak_tags_and_the_wildcard() { + let tag = "\"3-44cc4da1\""; + assert!(etag_matches(Some("\"x\", W/\"3-44cc4da1\""), tag)); + assert!(etag_matches(Some("*"), tag)); + assert!(!etag_matches(Some("\"x\""), tag)); + assert!(!etag_matches(None, tag)); + assert!(!etag_matches(Some(""), tag)); + } +} diff --git a/server/rust/metaobjects/src/providers.rs b/server/rust/metaobjects/src/providers.rs index c1254ef409..3f1415c142 100644 --- a/server/rust/metaobjects/src/providers.rs +++ b/server/rust/metaobjects/src/providers.rs @@ -238,6 +238,10 @@ fn children_of(v: &Value) -> Vec { fn parse_definition(file: &str, raw: &str) -> ProviderDefinition { let doc: Value = serde_json::from_str(raw) .unwrap_or_else(|e| panic!("spec/metamodel/{file}.json is not valid JSON: {e}")); + definition_of(&doc) +} + +fn definition_of(doc: &Value) -> ProviderDefinition { let types = doc .get("types") .and_then(Value::as_array) @@ -276,7 +280,7 @@ fn parse_definition(file: &str, raw: &str) -> ProviderDefinition { }) .unwrap_or_default(); ProviderDefinition { - provider: s(&doc, "provider").unwrap_or_default(), + provider: s(doc, "provider").unwrap_or_default(), types, extends, } @@ -484,6 +488,17 @@ fn define_from_data( Ok(out) } +/// Register a provider definition written in the shared `spec/metamodel/*.json` format +/// (its `types` and its `extends`), as the built-in providers register theirs. This is how +/// an application, or a test, adds vocabulary the core does not ship from data: call it +/// inside [`TypeRegistry::run_as_provider`] before sealing the registry. +pub fn apply_provider_definition( + registry: &mut TypeRegistry, + definition: &Value, +) -> Result<(), MetaError> { + apply_definition(registry, &definition_of(definition)) +} + fn apply_definition( registry: &mut TypeRegistry, data: &ProviderDefinition, diff --git a/server/rust/metaobjects/tests/docs_view_conformance.rs b/server/rust/metaobjects/tests/docs_view_conformance.rs new file mode 100644 index 0000000000..420731e69d --- /dev/null +++ b/server/rust/metaobjects/tests/docs_view_conformance.rs @@ -0,0 +1,119 @@ +//! The docs view corpus (`fixtures/explorer-conformance/`, `docs/features/docs-view.md`): each +//! fixture's project is loaded strictly, its committed optional inputs are read, and +//! [`docs_view::build`] must reproduce the fixture's `expected.json` byte for byte, as the +//! TypeScript reference does. A fixture's `provider.json` is registered before loading. +//! +//! Set `DOCS_VIEW_ACTUAL_DIR` to write each actual view there, for diffing. + +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +use metaobjects::collection::resolve_collection; +use metaobjects::docs_view; +use metaobjects::loader::Loader; +use metaobjects::naming::NamingRegistry; +use metaobjects::providers::{apply_provider_definition, compose_registry, core_providers}; + +fn corpus() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/explorer-conformance") +} + +fn read_json(dir: &Path, name: &str) -> Option { + let text = std::fs::read_to_string(dir.join(name)).ok()?; + Some(serde_json::from_str(&text).expect("a fixture input is JSON")) +} + +fn actual(dir: &Path) -> String { + let mut registry = compose_registry(&core_providers()).expect("the core providers compose"); + if let Some(def) = read_json(dir, "provider.json") { + let id = def["provider"].as_str().unwrap_or("fixture").to_string(); + registry + .run_as_provider(&id, |r| apply_provider_definition(r, &def)) + .expect("the fixture's provider registers"); + } + registry.seal(); + let project = dir.join("project"); + let collection = resolve_collection(&project, None, &NamingRegistry::builtin()) + .expect("the fixture's project resolves"); + let (sources, read_errors) = collection.read_sources(); + assert!(read_errors.is_empty(), "{read_errors:?}"); + let loaded = Loader::new(®istry).strict(true).load_sources(&sources); + assert!( + loaded.errors.is_empty(), + "{}: {:?}", + dir.display(), + loaded.errors + ); + let view = docs_view::build( + &loaded.tree, + loaded.root, + read_json(dir, "verify.json").as_ref(), + read_json(dir, "hashes.json").as_ref(), + read_json(dir, "routes.json").as_ref(), + ); + docs_view::serialize(&view) +} + +#[test] +fn every_fixture_reproduces_its_expected_view() { + let mut names: Vec = std::fs::read_dir(corpus()) + .expect("the corpus exists") + .filter_map(Result::ok) + .filter(|e| e.path().is_dir()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + assert!(names.len() >= 3, "the corpus has its fixtures: {names:?}"); + let out_dir = std::env::var_os("DOCS_VIEW_ACTUAL_DIR").map(PathBuf::from); + let mut failed = Vec::new(); + for name in &names { + let dir = corpus().join(name); + let got = actual(&dir); + if let Some(out) = &out_dir { + std::fs::create_dir_all(out).unwrap(); + std::fs::write(out.join(format!("{name}.json")), &got).unwrap(); + } + let want = std::fs::read_to_string(dir.join("expected.json")).unwrap(); + if got != want { + failed.push(name.clone()); + } + } + assert!( + failed.is_empty(), + "docs view differs from expected.json for {failed:?}" + ); +} + +#[test] +fn the_view_is_deterministic() { + let dir = corpus().join("shop"); + assert_eq!(actual(&dir), actual(&dir)); +} + +/// `GET /_meta/docs` is the docs view of the loaded model alone: over the fixture with no build +/// inputs, the route's body is that fixture's expected view, and its ETag is TypeScript's. +#[test] +fn the_docs_route_serves_the_model_alone_view() { + use metaobjects::meta_endpoint::{META_DOCS_ROUTE_PATH, META_ROUTE_PATH, docs, meta_json}; + let dir = corpus().join("model-alone"); + let registry = { + let mut r = compose_registry(&core_providers()).unwrap(); + r.seal(); + r + }; + let collection = + resolve_collection(&dir.join("project"), None, &NamingRegistry::builtin()).unwrap(); + let (sources, _) = collection.read_sources(); + let loaded = Loader::new(®istry).strict(true).load_sources(&sources); + let d = docs(&loaded.tree, loaded.root, None); + assert_eq!( + d.body, + std::fs::read_to_string(dir.join("expected.json")).unwrap() + ); + // metaDocsEtag(body) in @metaobjectsdev/runtime-ts over the same bytes. + assert_eq!(d.etag, "\"4c8c-0068e2ba\""); + assert!(d.matches(Some("\"4c8c-0068e2ba\""))); + assert_eq!(META_DOCS_ROUTE_PATH, format!("{META_ROUTE_PATH}/docs")); + assert!(meta_json(&loaded.tree, loaded.root).starts_with('{')); +} From a5417e2e7760129cf3f6c51a32fa8fdb526f579f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 06:12:00 -0500 Subject: [PATCH 02/21] no-mistakes(review): Close docs-site skip gaps, init list, dead API --- docs/ports/rust.md | 3 +- .../GenSkipConformanceTests.cs | 26 +++++++++++++ .../csharp/MetaObjects.Codegen/CodegenCli.cs | 10 ++++- .../csharp/MetaObjects.Codegen/Generator.cs | 8 ++++ .../Generators/DocsSiteGenerator.cs | 3 ++ server/python/src/metaobjects/cli.py | 8 ++++ .../src/metaobjects/codegen/generator.py | 8 ++++ .../codegen/generators/docs_site_generator.py | 13 ++++--- .../python/tests/test_gen_skip_conformance.py | 38 +++++++++++++++++++ server/rust/metaobjects-cli/src/lib.rs | 3 +- server/rust/metaobjects-codegen/build.rs | 12 ++++-- .../rust/metaobjects-codegen/src/docs_site.rs | 25 +++++++----- server/rust/metaobjects-codegen/src/engine.rs | 7 ++++ .../rust/metaobjects-codegen/src/generator.rs | 22 +++++++++++ .../metaobjects-codegen/src/generator_list.rs | 22 ++++++++--- .../metaobjects-codegen/tests/docs_site.rs | 34 ++++++++++++++++- server/rust/metaobjects/src/docs_view.rs | 5 --- 17 files changed, 212 insertions(+), 35 deletions(-) diff --git a/docs/ports/rust.md b/docs/ports/rust.md index b4aeb48501..2dd78f4e7e 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -70,7 +70,8 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log The generators a project runs are the list in `metaobjects.config.json` at the project root, the way the other ports choose theirs (`metaobjects.config.ts`, `codegen/Generators.cs`, the pom, `metaobjects.config.yaml`). `cargo meta init` writes every shipped generator but the opt-in -transport, `service-routes`, which `cargo meta init --transport` adds; delete a line to stop running +ones: the transport, `service-routes`, which `cargo meta init --transport` adds, and the two docs +generators, `metamodel-docs` and `docs-site`, which you add by name. Delete a line to stop running one, and no eject is needed: ```json diff --git a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs index ffa928e955..3ab19e77c6 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs @@ -53,6 +53,15 @@ public sealed class GenSkipConformanceTests : IDisposable ]}} """; + private const string NotePrompt = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "NoteRequest", "children": [ + { "field.string": { "name": "text" } } + ]}}, + { "template.prompt": { "name": "NotePrompt", "@payloadRef": "NoteRequest", "@textRef": "note-text", "@format": "text" } } + ]}} + """; + /// A generator that declares an extra input and can mark itself uncacheable. private sealed class Custom(bool cacheable) : IGenerator { @@ -316,6 +325,23 @@ public void An_entities_run_renders_never_stores_and_leaves_the_full_run_key_alo Assert.Contains(GenSkipped, RunGen(Declared()).Out); } + [Fact] + public void Editing_a_prompt_beside_the_metadata_regenerates_the_docs_site() + { + File.WriteAllText(P("metaobjects/meta.note.json"), NotePrompt); + File.WriteAllText(P("metaobjects/note-text.mustache"), "first text"); + IReadOnlyList declared = [.. Declared(), new DocsSiteGenerator()]; + var first = RunGen(declared); + Assert.True(first.Exit == 0, first.Out + first.Err); + var model = Path.Combine(OutDir, "site", "explorer-model.js"); + Assert.Contains("first text", File.ReadAllText(model)); + + File.WriteAllText(P("metaobjects/note-text.mustache"), "second text"); + Assert.Equal("regenerate", GenDecision(declared, [])); + Assert.Contains("second text", File.ReadAllText(model)); + Assert.DoesNotContain("first text", File.ReadAllText(model)); + } + [Fact] public void An_edit_regenerates_and_the_next_run_skips_again() { diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index cdfba9eab7..1560fa76e7 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -709,6 +709,12 @@ private static int RunGenArgs(string[] rest, IReadOnlyList declared, TemplateSpec = a.TemplateSpecPath, Entities = a.Entities, EmitAbstractShapes = a.EmitAbstractShapes, Strict = a.Strict, Baseline = a.Baseline, }; + /// The extra inputs of a run: every entry's , and the + /// metadata directory when an entry reads files beside the metadata. + private static IEnumerable KeyExtras(IReadOnlyList suite, ResolvedMetadata meta) => + suite.SelectMany(g => g.ExtraInputs) + .Concat(suite.Any(g => g.ReadsMetadataDirectory) ? [meta.Directory] : []); + private static int RunGenCore(string[] rest, IReadOnlyList declared, KeyGate gate, Func? configure) { var a = OwnedArgs.Parse(rest, GenCommandName, GenValueFlags, GenBoolFlags); @@ -841,7 +847,7 @@ private static int RunGenCore(string[] rest, IReadOnlyList declared, var cwd = Directory.GetCurrentDirectory(); var modelHash = ModelHash.Of(genLoad.Root).Model; var identity = GenFingerprint.Key(GenFingerprint.IdentityEntries( - projectRoot, cwd, KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), suite.SelectMany(g => g.ExtraInputs))); + projectRoot, cwd, KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), KeyExtras(suite, meta))); // An --entities run is narrowed and forces exactly those entities: it never skips, never // stores a key, and leaves the stored full-run key alone (it can neither write nor satisfy it). var wholeRun = a.Entities is null; @@ -1098,7 +1104,7 @@ private static int RunVerifyArgs(string[] rest, IReadOnlyList declar projectRoot, ModelHash.Of(load.Root).Model, GenFingerprint.Key(GenFingerprint.IdentityEntries( projectRoot, Directory.GetCurrentDirectory(), KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), - suite.SelectMany(g => g.ExtraInputs))), + KeyExtras(suite, meta))), a.Full)) { Console.WriteLine($"{VerifyCommandName}: OK (nothing changed since the last gen; --full renders and compares)"); diff --git a/server/csharp/MetaObjects.Codegen/Generator.cs b/server/csharp/MetaObjects.Codegen/Generator.cs index 36fffe6a4b..5fa00a3946 100644 --- a/server/csharp/MetaObjects.Codegen/Generator.cs +++ b/server/csharp/MetaObjects.Codegen/Generator.cs @@ -673,6 +673,12 @@ public interface IGenerator /// The runner runs every such entry after every other one, keeping their declared order. /// bool ReadsRunOutput => false; + + /// + /// ADR-0064 — whether this entry reads files beside the metadata, in the metadata directory + /// (prompt texts). That directory then joins the run's identity, whole. + /// + bool ReadsMetadataDirectory => false; } /// A generator entry's handEdits setting: what a run does with a hand-edited file. @@ -714,6 +720,8 @@ internal sealed class HandEditsGenerator(IGenerator inner, HandEdits handEdits) public IReadOnlyList ExtraInputs => Inner.ExtraInputs; public bool ReadsRunOutput => Inner.ReadsRunOutput; /// + public bool ReadsMetadataDirectory => Inner.ReadsMetadataDirectory; + /// public IEnumerable Generate(GenContext ctx) => Inner.Generate(ctx); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs index 3bc5525f09..f9f60186a9 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs @@ -54,6 +54,9 @@ public sealed class DocsSiteGenerator : IGenerator public IReadOnlyList ExtraInputs => new[] { OwnedDocsSiteDir, Prompts, VerifyFile, RoutesFile }.OfType().ToList(); + /// Prompt texts beside the metadata are read too, so the metadata directory is an input. + public bool ReadsMetadataDirectory => true; + public IEnumerable Generate(GenContext ctx) { // A run that names no project reads nothing beside the model it was handed: no committed diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index 536fc3f7f4..b5ed92deb6 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -137,6 +137,7 @@ SelectedGenerator, generator_cacheable, generator_extra_inputs, + generator_reads_metadata_dir, ) from metaobjects.codegen import model_key, skip from metaobjects.codegen.generators.entity_model import entity_model @@ -1844,6 +1845,13 @@ def selected(gen: Generator, token: str) -> bool: every = [g for _t, gens, spec_gens, _o in plan for g in (*gens, *spec_gens)] skip_info.cacheable = all(generator_cacheable(g) for g in every) skip_info.extras = {p for g in every for p in generator_extra_inputs(g)} + if any(generator_reads_metadata_dir(g) for g in every): + meta_dir = Path(config.metadata_dir()).resolve() + try: + meta_rel = meta_dir.relative_to(Path(project_root or ".").resolve()).as_posix() + except ValueError: + meta_rel = str(meta_dir) + skip_info.extras.add(meta_rel) skip_info.extra_entries = skip.extras_entries( Path(project_root or "."), skip_info.extras) diff --git a/server/python/src/metaobjects/codegen/generator.py b/server/python/src/metaobjects/codegen/generator.py index ea689e7d65..87d5380f70 100644 --- a/server/python/src/metaobjects/codegen/generator.py +++ b/server/python/src/metaobjects/codegen/generator.py @@ -79,6 +79,9 @@ class Generator(Protocol): - ``declared_extra_inputs: tuple[str, ...]`` (default ``()``). Project-relative paths the generator reads beyond the model, the config and the template roots; their content is part of the run's key. + - ``reads_metadata_dir: bool`` (default ``False``). ``True`` means the generator reads + files beside the metadata (prompt texts); the metadata directory is then part of the + run's key, whole. """ name: str @@ -143,6 +146,11 @@ def generator_extra_inputs(gen: object) -> tuple[str, ...]: return tuple(getattr(gen, "declared_extra_inputs", ()) or ()) +def generator_reads_metadata_dir(gen: object) -> bool: + """Whether ``gen`` reads files beside the metadata, in the metadata directory.""" + return bool(getattr(gen, "reads_metadata_dir", False)) + + def per_entity( fn: Callable[[MetaObject, GenContext], "EmittedFile | list[EmittedFile]"], ) -> Callable[[GenContext], list[EmittedFile]]: diff --git a/server/python/src/metaobjects/codegen/generators/docs_site_generator.py b/server/python/src/metaobjects/codegen/generators/docs_site_generator.py index e0626101f9..f01c3b4c7e 100644 --- a/server/python/src/metaobjects/codegen/generators/docs_site_generator.py +++ b/server/python/src/metaobjects/codegen/generators/docs_site_generator.py @@ -166,6 +166,8 @@ class DocsSiteGenerator: name = "docs-site" #: The runner runs a generator that reads the run's output after every other one. reads_run_output = True + #: Prompt texts beside the metadata are read, so the metadata directory is an input. + reads_metadata_dir = True def __init__( self, @@ -182,12 +184,13 @@ def __init__( self.prompts = prompts self.verify_file = verify_file self.routes_file = routes_file - #: The owned theme, the prompts directory and the verify and routes files are read beside - #: the model (ADR-0064): editing one regenerates. The hash manifest is not an input: the - #: files the site lists are this run's and the manifest's, and the whole-run skip already - #: re-runs when the manifest gains, loses or changes a file. + #: The owned theme, ``templates/``, the prompts directory and the verify and routes files + #: are read beside the model (ADR-0064), and so is the metadata directory + #: (``reads_metadata_dir``): editing one regenerates. The hash manifest is not an input: + #: the files the site lists are this run's and the manifest's, and the whole-run skip + #: already re-runs when the manifest gains, loses or changes a file. self.declared_extra_inputs: tuple[str, ...] = tuple( - p for p in (OWNED_DOCS_SITE_DIR, prompts, verify_file, routes_file) if p + p for p in (OWNED_DOCS_SITE_DIR, "templates", prompts, verify_file, routes_file) if p ) def generate(self, ctx: GenContext) -> list[EmittedFile]: diff --git a/server/python/tests/test_gen_skip_conformance.py b/server/python/tests/test_gen_skip_conformance.py index 75b5e0dd01..e78d9ed3ba 100644 --- a/server/python/tests/test_gen_skip_conformance.py +++ b/server/python/tests/test_gen_skip_conformance.py @@ -429,3 +429,41 @@ def test_a_run_that_names_entities_renders_and_leaves_the_full_run_key_alone( # It neither wrote nor forgot the full-run key, so the next full run still skips. assert stored.read_bytes() == key assert h.gen() == (0, True) + + +_NOTE_PROMPT = { + "metadata.root": { + "package": "skip", + "children": [ + {"object.value": {"name": "NoteRequest", "children": [ + {"field.string": {"name": "text"}}, + ]}}, + {"template.prompt": { + "name": "NotePrompt", "@payloadRef": "NoteRequest", + "@textRef": "note-text", "@format": "text", + }}, + ], + } +} + + +def test_editing_a_prompt_in_templates_regenerates_the_docs_site( + tmp_path: Path, monkeypatch, capsys +) -> None: + project = _project(tmp_path) + (tmp_path / "metaobjects" / "meta.note.json").write_text(json.dumps(_NOTE_PROMPT)) + (tmp_path / "templates").mkdir() + prompt = tmp_path / "templates" / "note-text.mustache" + prompt.write_text("first text") + project.write_config("[entity, docs-site]") + h = Harness(project, monkeypatch, capsys) + rc, skipped = h.gen() + assert rc == 0 and not skipped, h.out + h.err + model = tmp_path / "generated" / "site" / "explorer-model.js" + assert "first text" in model.read_text() + + prompt.write_text("second text") + rc, skipped = h.gen() + assert rc == 0 and not skipped, "an edited prompt is an input" + text = model.read_text() + assert "second text" in text and "first text" not in text diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 7f6a47de85..4ea4c4c6ca 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -95,7 +95,8 @@ OPTIONS (everywhere): GENERATORS: a project chooses what runs in metaobjects.config.json, `{ \"generators\": [..] }`, by name. Edit the list; no eject is needed. With no such file every generator runs but the -opt-in transport (service-routes), which `init --transport` lists. +opt-in ones: the transport (service-routes), which `init --transport` lists, and the docs +generators (metamodel-docs, docs-site), which run only when listed. ENTITY names limit `gen` to the crates that contain them plus the crates those depend on. Such a run never skips, never stores the skip key and never removes a file. diff --git a/server/rust/metaobjects-codegen/build.rs b/server/rust/metaobjects-codegen/build.rs index b32ec70571..53a78f84ec 100644 --- a/server/rust/metaobjects-codegen/build.rs +++ b/server/rust/metaobjects-codegen/build.rs @@ -20,10 +20,12 @@ fn collect(dir: &Path, out: &mut Vec) { for p in entries { if p.is_dir() { collect(&p, out); - } else if p - .extension() - .is_some_and(|e| e == "rs" || e == "toml" || e == "mustache" || e == "json") - { + } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| { + matches!( + e, + "rs" | "toml" | "mustache" | "json" | "js" | "css" | "html" + ) + }) { out.push(p); } } @@ -39,6 +41,8 @@ fn main() { // The shipped Mustache templates and the embedded metamodel provider definitions. manifest.join("templates"), manifest.join("../metaobjects/data"), + // The shipped explorer app the docs-site generator copies. + manifest.join("explorer-app"), ]; let mut hasher = sha256::Sha256::new(); for root in &roots { diff --git a/server/rust/metaobjects-codegen/src/docs_site.rs b/server/rust/metaobjects-codegen/src/docs_site.rs index 433bd945d7..9a37dbfe55 100644 --- a/server/rust/metaobjects-codegen/src/docs_site.rs +++ b/server/rust/metaobjects-codegen/src/docs_site.rs @@ -167,6 +167,10 @@ impl Generator for DocsSiteGenerator { true } + fn reads_source_dirs(&self) -> bool { + true + } + fn configure(&self, options: &Options) -> Result, GenError> { Ok(Box::new(DocsSite::from_options(options)?)) } @@ -185,11 +189,12 @@ impl Generator for DocsSite { format!("{NAME}:{FORMAT}:{self:?}") } - /// The owned theme, the prompts directory and the verify and routes files are read beside - /// the model (ADR-0064): editing one regenerates. The hash manifest is not an input here: - /// the whole-run skip already re-runs when a recorded file changes or goes. + /// The owned theme, `templates/`, the prompts directory and the verify and routes files are + /// read beside the model (ADR-0064), and so are the metadata directories + /// ([`Generator::reads_source_dirs`]): editing one regenerates. The hash manifest is not an + /// input here: the whole-run skip already re-runs when a recorded file changes or goes. fn extra_inputs(&self) -> Vec { - let mut inputs = vec![OWNED_DOCS_SITE_DIR.to_string()]; + let mut inputs = vec![OWNED_DOCS_SITE_DIR.to_string(), TEMPLATES_DIR.to_string()]; inputs.extend(self.prompts.clone()); inputs.extend(self.verify_file.clone()); inputs.extend(self.routes_file.clone()); @@ -200,6 +205,10 @@ impl Generator for DocsSite { true } + fn reads_source_dirs(&self) -> bool { + true + } + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { let project = &ctx.collection.config_dir; let verify = self @@ -292,12 +301,8 @@ impl DocsSite { dirs.push(d); } }; - for root in &ctx.collection.source_roots { - add(if root.is_dir() { - root.clone() - } else { - root.parent().map(Path::to_path_buf).unwrap_or_default() - }); + for dir in crate::generator::source_dirs(&ctx.collection.source_roots) { + add(dir); } add(project.join(TEMPLATES_DIR)); if let Some(p) = &self.prompts { diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index 6a8f9ccd24..0e61dd4ffc 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -728,6 +728,13 @@ fn prepare<'g>( let digest = hash_tree(&project_root.join(&extra)); entries.push(InputEntry::new(KIND_EXTRA, extra, digest)); } + if g.reads_source_dirs() { + for dir in crate::generator::source_dirs(&loaded.collection.source_roots) { + let name = dir.strip_prefix(&project_root).unwrap_or(&dir); + let name = name.to_string_lossy().replace('\\', "/"); + entries.push(InputEntry::new(KIND_EXTRA, name, hash_tree(&dir))); + } + } } // The owned generator crate, whole: the generator list is the adopter's file and may pull // in any module beside it (`mod util;`), so naming the files the scaffold writes would diff --git a/server/rust/metaobjects-codegen/src/generator.rs b/server/rust/metaobjects-codegen/src/generator.rs index c582a43182..bf223860ef 100644 --- a/server/rust/metaobjects-codegen/src/generator.rs +++ b/server/rust/metaobjects-codegen/src/generator.rs @@ -6,6 +6,7 @@ use std::collections::BTreeSet; use std::fmt; +use std::path::{Path, PathBuf}; use metaobjects::collection::Collection; use metaobjects::node::{NodeId, Tree}; @@ -176,6 +177,27 @@ pub trait Generator { false } + /// Whether this generator reads files beside the metadata, in the directories the model was + /// loaded from (prompt texts). Those directories are then part of the skip key, whole. + fn reads_source_dirs(&self) -> bool { + false + } + /// Produce the generator's files for the loaded model. fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError>; } + +/// The directories the model was loaded from: each source root, or the directory of a root +/// that is a file. +pub(crate) fn source_dirs(roots: &[PathBuf]) -> Vec { + roots + .iter() + .map(|root| { + if root.is_dir() { + root.clone() + } else { + root.parent().map(Path::to_path_buf).unwrap_or_default() + } + }) + .collect() +} diff --git a/server/rust/metaobjects-codegen/src/generator_list.rs b/server/rust/metaobjects-codegen/src/generator_list.rs index 04dc05f103..9723b5fbe1 100644 --- a/server/rust/metaobjects-codegen/src/generator_list.rs +++ b/server/rust/metaobjects-codegen/src/generator_list.rs @@ -177,6 +177,9 @@ pub fn check(names: &[String], available: &[&str]) -> Result<(), String> { Ok(()) } +/// The opt-in axum transport, the one opt-in generator `cargo meta init --transport` lists. +const TRANSPORT: &str = "service-routes"; + /// Every shipped generator's name, in the order a run applies them. pub fn shipped_names() -> Vec<&'static str> { eject::REFERENCES.iter().map(|r| r.name).collect() @@ -198,13 +201,13 @@ fn example() -> String { ) } -/// The text `cargo meta init` writes: every shipped generator but the opt-in ones, and those -/// too with `opt_in`, so a new project generates what it always has and removes one by deleting -/// a line. -pub fn scaffold(opt_in: bool) -> String { +/// The text `cargo meta init` writes: every shipped generator but the opt-in ones, and the axum +/// transport (`service-routes`) too with `transport`, so a new project generates what it always +/// has and removes one by deleting a line. The docs generators are never listed. +pub fn scaffold(transport: bool) -> String { let items = eject::REFERENCES .iter() - .filter(|r| opt_in || !r.opt_in) + .filter(|r| !r.opt_in || (transport && r.name == TRANSPORT)) .map(|r| format!(" \"{}\"", r.name)) .collect::>() .join(",\n"); @@ -238,11 +241,18 @@ mod tests { ); assert!(check(&names(&parse(&scaffold(false)).unwrap()), &shipped_names()).is_ok()); let all = names(&parse(&scaffold(true)).unwrap()); - assert_eq!(all, s(&shipped_names())); + let mut without_transport = all.clone(); + without_transport.retain(|n| n != "service-routes"); + assert_eq!(all.len(), without_transport.len() + 1); + assert_eq!(without_transport, names(&parse(&scaffold(false)).unwrap())); assert!(check(&all, &shipped_names()).is_ok()); + for docs in ["metamodel-docs", "docs-site"] { + assert!(!all.iter().any(|n| n == docs), "{docs}"); + } assert!( !runs_unlisted("service-routes") && !runs_unlisted("metamodel-docs") + && !runs_unlisted("docs-site") && runs_unlisted("entity") ); } diff --git a/server/rust/metaobjects-codegen/tests/docs_site.rs b/server/rust/metaobjects-codegen/tests/docs_site.rs index dba9c2ba74..d7fcd71420 100644 --- a/server/rust/metaobjects-codegen/tests/docs_site.rs +++ b/server/rust/metaobjects-codegen/tests/docs_site.rs @@ -12,7 +12,7 @@ use metaobjects_codegen::docs_site::{ read_prompt_texts, }; use metaobjects_codegen::sha256::sha256_hex; -use metaobjects_codegen::{RunOptions, run, shipped_generators, verify}; +use metaobjects_codegen::{Outcome, RunOptions, run, shipped_generators, verify}; use serde_json::Value; fn repo() -> PathBuf { @@ -218,6 +218,38 @@ fn a_run_writes_the_explorer_over_the_files_the_manifest_records() { ); } +#[test] +fn editing_a_prompt_beside_the_metadata_or_in_templates_regenerates_the_site() { + for dir in ["metaobjects", "templates"] { + let p = Scratch::project(&format!("docs-site-prompt-{dir}"), &[]); + copy_dir(&fixture("shop").join("project"), p.path()); + std::fs::remove_dir_all(p.path().join("prompts")).unwrap(); + let prompt = format!("{dir}/shop/order-note.mustache"); + p.write(&prompt, "first text"); + p.write( + "metaobjects.config.json", + r#"{ "generators": [{ "name": "docs-site", "options": { "subDir": "" } }] }"#, + ); + let mut opts = RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); + assert!(p.read("generated/explorer-model.js").contains("first text")); + + p.write(&prompt, "second text"); + let r = run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); + assert_ne!( + r.outcome, + Outcome::Skipped, + "{dir}: an edited prompt is an input" + ); + let model = p.read("generated/explorer-model.js"); + assert!( + model.contains("second text") && !model.contains("first text"), + "{dir}: the site carries the edited prompt" + ); + } +} + #[test] fn a_project_with_no_list_does_not_run_it() { let p = Scratch::project("docs-site-unlisted", &common::shop_files()); diff --git a/server/rust/metaobjects/src/docs_view.rs b/server/rust/metaobjects/src/docs_view.rs index bf8feb95be..e8e90b5578 100644 --- a/server/rust/metaobjects/src/docs_view.rs +++ b/server/rust/metaobjects/src/docs_view.rs @@ -104,11 +104,6 @@ pub fn stamp_script(stamp: &str) -> String { format!("window.MO_STAMP = {};\n", js_quote(stamp)) } -/// The docs view of the model alone. -pub fn build_model(tree: &Tree, root: NodeId) -> Value { - build(tree, root, None, None, None) -} - /// Build the docs view of the model at `root`. `verify`, `manifest` and `routes` are optional; /// a malformed one only leaves its part out. pub fn build( From 6010c7cea881e057ce88f3c8aafbcd2f4f440415 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 06:22:04 -0500 Subject: [PATCH 03/21] no-mistakes(review): Key docs-site skip on prompt files, not dirs --- .../GenSkipConformanceTests.cs | 3 +- .../csharp/MetaObjects.Codegen/CodegenCli.cs | 13 ++- .../MetaObjects.Codegen/Docs/ExplorerSite.cs | 27 ++++-- .../csharp/MetaObjects.Codegen/Generator.cs | 8 +- .../Generators/DocsSiteGenerator.cs | 25 ++++-- server/python/src/metaobjects/cli.py | 16 ++-- .../src/metaobjects/codegen/generator.py | 14 +-- .../metaobjects/codegen/generator_registry.py | 2 +- .../codegen/generators/docs_site_generator.py | 54 ++++++++---- .../python/tests/test_gen_skip_conformance.py | 27 ++++-- .../rust/metaobjects-codegen/src/docs_site.rs | 88 ++++++++++++------- server/rust/metaobjects-codegen/src/engine.rs | 10 +-- .../rust/metaobjects-codegen/src/generator.rs | 25 ++---- .../metaobjects-codegen/tests/docs_site.rs | 44 ++++++++-- 14 files changed, 224 insertions(+), 132 deletions(-) diff --git a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs index 3ab19e77c6..413722331f 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs @@ -326,7 +326,7 @@ public void An_entities_run_renders_never_stores_and_leaves_the_full_run_key_alo } [Fact] - public void Editing_a_prompt_beside_the_metadata_regenerates_the_docs_site() + public void An_unchanged_run_skips_and_an_edited_prompt_beside_the_metadata_regenerates_the_docs_site() { File.WriteAllText(P("metaobjects/meta.note.json"), NotePrompt); File.WriteAllText(P("metaobjects/note-text.mustache"), "first text"); @@ -335,6 +335,7 @@ public void Editing_a_prompt_beside_the_metadata_regenerates_the_docs_site() Assert.True(first.Exit == 0, first.Out + first.Err); var model = Path.Combine(OutDir, "site", "explorer-model.js"); Assert.Contains("first text", File.ReadAllText(model)); + Assert.Equal("skip", GenDecision(declared, [])); File.WriteAllText(P("metaobjects/note-text.mustache"), "second text"); Assert.Equal("regenerate", GenDecision(declared, [])); diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index 1560fa76e7..34d146a708 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -709,11 +709,10 @@ private static int RunGenArgs(string[] rest, IReadOnlyList declared, TemplateSpec = a.TemplateSpecPath, Entities = a.Entities, EmitAbstractShapes = a.EmitAbstractShapes, Strict = a.Strict, Baseline = a.Baseline, }; - /// The extra inputs of a run: every entry's , and the - /// metadata directory when an entry reads files beside the metadata. - private static IEnumerable KeyExtras(IReadOnlyList suite, ResolvedMetadata meta) => - suite.SelectMany(g => g.ExtraInputs) - .Concat(suite.Any(g => g.ReadsMetadataDirectory) ? [meta.Directory] : []); + /// The extra inputs of a run: every entry's and + /// . + private static IEnumerable KeyExtras(IReadOnlyList suite, MetaRoot root, string projectRoot) => + suite.SelectMany(g => g.ExtraInputs).Concat(suite.SelectMany(g => g.ModelInputs(root, projectRoot))); private static int RunGenCore(string[] rest, IReadOnlyList declared, KeyGate gate, Func? configure) { @@ -847,7 +846,7 @@ private static int RunGenCore(string[] rest, IReadOnlyList declared, var cwd = Directory.GetCurrentDirectory(); var modelHash = ModelHash.Of(genLoad.Root).Model; var identity = GenFingerprint.Key(GenFingerprint.IdentityEntries( - projectRoot, cwd, KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), KeyExtras(suite, meta))); + projectRoot, cwd, KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), KeyExtras(suite, genLoad.Root, projectRoot))); // An --entities run is narrowed and forces exactly those entities: it never skips, never // stores a key, and leaves the stored full-run key alone (it can neither write nor satisfy it). var wholeRun = a.Entities is null; @@ -1104,7 +1103,7 @@ private static int RunVerifyArgs(string[] rest, IReadOnlyList declar projectRoot, ModelHash.Of(load.Root).Model, GenFingerprint.Key(GenFingerprint.IdentityEntries( projectRoot, Directory.GetCurrentDirectory(), KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), - KeyExtras(suite, meta))), + KeyExtras(suite, load.Root, projectRoot))), a.Full)) { Console.WriteLine($"{VerifyCommandName}: OK (nothing changed since the last gen; --full renders and compares)"); diff --git a/server/csharp/MetaObjects.Codegen/Docs/ExplorerSite.cs b/server/csharp/MetaObjects.Codegen/Docs/ExplorerSite.cs index f816227fa7..ab9714120f 100644 --- a/server/csharp/MetaObjects.Codegen/Docs/ExplorerSite.cs +++ b/server/csharp/MetaObjects.Codegen/Docs/ExplorerSite.cs @@ -97,16 +97,9 @@ public static SortedDictionary ReadPromptTexts(JsonObject view, && attr["value"] is JsonValue v && v.TryGetValue(out var s)) textRef = s; } - if (textRef is null) continue; - var segments = textRef.Split('/', '\\'); - bool unsafeRef = Path.IsPathRooted(textRef) || textRef.StartsWith('/') || textRef.StartsWith('\\') - || segments.Any(seg => seg.Length == 0 || seg == ".."); - if (unsafeRef) continue; - foreach (var dir in dirs) + if (textRef is null || PromptCandidates(textRef, dirs) is not { } candidates) continue; + foreach (var p in candidates) { - var parts = segments.ToArray(); - parts[^1] += ".mustache"; - var p = Path.Combine([dir, .. parts]); if (!File.Exists(p)) continue; texts[node["id"]!.GetValue()] = File.ReadAllText(p); break; @@ -115,6 +108,22 @@ public static SortedDictionary ReadPromptTexts(JsonObject view, return texts; } + /// + /// Where a @textRef is looked for, in search order: <dir>/<ref>.mustache for + /// each of . null for a ref that is absolute or climbs out with + /// .., which is never read. + /// + public static IReadOnlyList? PromptCandidates(string textRef, IReadOnlyList dirs) + { + var segments = textRef.Split('/', '\\'); + bool unsafeRef = Path.IsPathRooted(textRef) || textRef.StartsWith('/') || textRef.StartsWith('\\') + || segments.Any(seg => seg.Length == 0 || seg == ".."); + if (unsafeRef) return null; + var parts = segments.ToArray(); + parts[^1] += ".mustache"; + return [.. dirs.Select(dir => Path.Combine([dir, .. parts]))]; + } + private static string? ReadIfPresent(string? dir, string name) { if (dir is null) return null; diff --git a/server/csharp/MetaObjects.Codegen/Generator.cs b/server/csharp/MetaObjects.Codegen/Generator.cs index 5fa00a3946..7c7892139f 100644 --- a/server/csharp/MetaObjects.Codegen/Generator.cs +++ b/server/csharp/MetaObjects.Codegen/Generator.cs @@ -675,10 +675,10 @@ public interface IGenerator bool ReadsRunOutput => false; /// - /// ADR-0064 — whether this entry reads files beside the metadata, in the metadata directory - /// (prompt texts). That directory then joins the run's identity, whole. + /// ADR-0064 — the files this entry reads because the loaded model names them (a prompt's + /// @textRef text), each one present or not. Their content joins the run's identity. /// - bool ReadsMetadataDirectory => false; + IReadOnlyList ModelInputs(MetaRoot root, string projectRoot) => []; } /// A generator entry's handEdits setting: what a run does with a hand-edited file. @@ -720,7 +720,7 @@ internal sealed class HandEditsGenerator(IGenerator inner, HandEdits handEdits) public IReadOnlyList ExtraInputs => Inner.ExtraInputs; public bool ReadsRunOutput => Inner.ReadsRunOutput; /// - public bool ReadsMetadataDirectory => Inner.ReadsMetadataDirectory; + public IReadOnlyList ModelInputs(MetaRoot root, string projectRoot) => Inner.ModelInputs(root, projectRoot); /// public IEnumerable Generate(GenContext ctx) => Inner.Generate(ctx); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs index f9f60186a9..e55d0da7e7 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DocsSiteGenerator.cs @@ -11,6 +11,8 @@ using System.Text.Json.Nodes; using MetaObjects.Codegen.Docs; using MetaObjects.Config; +using MetaObjects.Meta; +using static MetaObjects.Template.TemplateConstants; namespace MetaObjects.Codegen.Generators; @@ -54,8 +56,21 @@ public sealed class DocsSiteGenerator : IGenerator public IReadOnlyList ExtraInputs => new[] { OwnedDocsSiteDir, Prompts, VerifyFile, RoutesFile }.OfType().ToList(); - /// Prompt texts beside the metadata are read too, so the metadata directory is an input. - public bool ReadsMetadataDirectory => true; + /// Every path a prompt's @textRef may be read from, in every directory searched. + public IReadOnlyList ModelInputs(MetaRoot root, string projectRoot) + { + var dirs = PromptDirs(Path.GetFullPath(projectRoot), projectKnown: true, warn: null); + var files = new SortedSet(StringComparer.Ordinal); + var stack = new Stack([root]); + while (stack.TryPop(out var node)) + { + if (node.Attr(TEMPLATE_ATTR_TEXT_REF) is string textRef + && ExplorerSite.PromptCandidates(textRef, dirs) is { } candidates) + files.UnionWith(candidates); + foreach (var child in node.Children()) stack.Push(child); + } + return [.. files]; + } public IEnumerable Generate(GenContext ctx) { @@ -80,7 +95,7 @@ public IEnumerable Generate(GenContext ctx) view, Title ?? (known is not null && Path.GetFileName(project.TrimEnd(Path.DirectorySeparatorChar)) is { Length: > 0 } dir ? dir : "Metadata"), Stamp, - ExplorerSite.ReadPromptTexts(view, PromptDirs(ctx, project, known is not null)), + ExplorerSite.ReadPromptTexts(view, PromptDirs(project, known is not null, ctx.Warn)), known is not null && Directory.Exists(assets) ? assets : null, known is not null && Directory.Exists(templates) ? templates : null)); var prefix = SubDir.TrimEnd('/') is { Length: > 0 } sub ? sub + "/" : ""; @@ -102,7 +117,7 @@ private static JsonObject ProvenanceJson(IReadOnlyDictionaryWhere a template's @textRef is looked up: the metadata directory, the /// project's templates/ and prompts/, then . - private List PromptDirs(GenContext ctx, string project, bool projectKnown) + private List PromptDirs(string project, bool projectKnown, Action? warn) { var dirs = new List(); void Add(string? d) @@ -122,7 +137,7 @@ void Add(string? d) if (Prompts is not null) { if (Directory.Exists(Path.Combine(project, Prompts))) Add(Prompts); - else ctx.Warn($"docs-site: the prompts directory does not exist: {Prompts}"); + else warn?.Invoke($"docs-site: the prompts directory does not exist: {Prompts}"); } return dirs; } diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index b5ed92deb6..33d56713f0 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -137,7 +137,7 @@ SelectedGenerator, generator_cacheable, generator_extra_inputs, - generator_reads_metadata_dir, + generator_model_inputs, ) from metaobjects.codegen import model_key, skip from metaobjects.codegen.generators.entity_model import entity_model @@ -1845,13 +1845,13 @@ def selected(gen: Generator, token: str) -> bool: every = [g for _t, gens, spec_gens, _o in plan for g in (*gens, *spec_gens)] skip_info.cacheable = all(generator_cacheable(g) for g in every) skip_info.extras = {p for g in every for p in generator_extra_inputs(g)} - if any(generator_reads_metadata_dir(g) for g in every): - meta_dir = Path(config.metadata_dir()).resolve() - try: - meta_rel = meta_dir.relative_to(Path(project_root or ".").resolve()).as_posix() - except ValueError: - meta_rel = str(meta_dir) - skip_info.extras.add(meta_rel) + base = Path(project_root or ".").resolve() + for g in every: + for f in generator_model_inputs(g, root, base): + try: + skip_info.extras.add(f.relative_to(base).as_posix()) + except ValueError: + skip_info.extras.add(str(f)) skip_info.extra_entries = skip.extras_entries( Path(project_root or "."), skip_info.extras) diff --git a/server/python/src/metaobjects/codegen/generator.py b/server/python/src/metaobjects/codegen/generator.py index 87d5380f70..90eec55aee 100644 --- a/server/python/src/metaobjects/codegen/generator.py +++ b/server/python/src/metaobjects/codegen/generator.py @@ -3,6 +3,7 @@ from __future__ import annotations from dataclasses import dataclass, field +from pathlib import Path from typing import Callable, Protocol from metaobjects.meta.core.object.meta_object import MetaObject @@ -79,9 +80,9 @@ class Generator(Protocol): - ``declared_extra_inputs: tuple[str, ...]`` (default ``()``). Project-relative paths the generator reads beyond the model, the config and the template roots; their content is part of the run's key. - - ``reads_metadata_dir: bool`` (default ``False``). ``True`` means the generator reads - files beside the metadata (prompt texts); the metadata directory is then part of the - run's key, whole. + - ``model_inputs(root, project_root) -> list[Path]`` (default none). The files the + generator reads because the loaded model names them (a prompt's ``@textRef`` text), + each one present or not; their content is part of the run's key. """ name: str @@ -146,9 +147,10 @@ def generator_extra_inputs(gen: object) -> tuple[str, ...]: return tuple(getattr(gen, "declared_extra_inputs", ()) or ()) -def generator_reads_metadata_dir(gen: object) -> bool: - """Whether ``gen`` reads files beside the metadata, in the metadata directory.""" - return bool(getattr(gen, "reads_metadata_dir", False)) +def generator_model_inputs(gen: object, root: object, project_root: Path) -> list[Path]: + """The files ``gen`` reads because the loaded model names them.""" + inputs = getattr(gen, "model_inputs", None) + return list(inputs(root, project_root)) if callable(inputs) else [] def per_entity( diff --git a/server/python/src/metaobjects/codegen/generator_registry.py b/server/python/src/metaobjects/codegen/generator_registry.py index 4d7d0caa3b..ef5fdb6a95 100644 --- a/server/python/src/metaobjects/codegen/generator_registry.py +++ b/server/python/src/metaobjects/codegen/generator_registry.py @@ -573,7 +573,7 @@ def _render_helper_default(ctx: GeneratorBuildContext) -> Generator: ), tier="neutral", layer="docs", - factory=lambda ctx: docs_site_generator(**ctx.options), + factory=lambda ctx: docs_site_generator(**ctx.options, source_files=ctx.source_files or ()), # Not ejectable: the site builder is engine (ADR-0034 Amendment 9); what an adopter owns # is the theme under codegen/docs-site/. source=None, diff --git a/server/python/src/metaobjects/codegen/generators/docs_site_generator.py b/server/python/src/metaobjects/codegen/generators/docs_site_generator.py index f01c3b4c7e..12b745de16 100644 --- a/server/python/src/metaobjects/codegen/generators/docs_site_generator.py +++ b/server/python/src/metaobjects/codegen/generators/docs_site_generator.py @@ -111,19 +111,22 @@ def read_prompt_texts(view: dict[str, Any], dirs: list[Path]) -> dict[str, str]: for a in n["attrs"]: if a["name"] == TEMPLATE_ATTR_TEXT_REF and isinstance(a["value"], str): ref = a["value"] - if ref is None: - continue - segments = ref.replace("\\", "/").split("/") - if ref.startswith(("/", "\\")) or os.path.isabs(ref) or any(s in ("", "..") for s in segments): - continue - for d in dirs: - p = d.joinpath(*segments[:-1], segments[-1] + ".mustache") + for p in _prompt_candidates(ref, dirs) if ref is not None else (): if p.is_file(): out[n["id"]] = p.read_text(encoding="utf-8") break return dict(sorted(out.items())) +def _prompt_candidates(ref: str, dirs: list[Path]) -> list[Path]: + """Where a ``@textRef`` is looked for, in search order: ``/.mustache`` for each of + *dirs*. Empty for a ref that is absolute or climbs out with ``..``, which is never read.""" + segments = ref.replace("\\", "/").split("/") + if ref.startswith(("/", "\\")) or os.path.isabs(ref) or any(s in ("", "..") for s in segments): + return [] + return [d.joinpath(*segments[:-1], segments[-1] + ".mustache") for d in dirs] + + def emit_site( view: dict[str, Any], title: str, @@ -166,8 +169,6 @@ class DocsSiteGenerator: name = "docs-site" #: The runner runs a generator that reads the run's output after every other one. reads_run_output = True - #: Prompt texts beside the metadata are read, so the metadata directory is an input. - reads_metadata_dir = True def __init__( self, @@ -177,6 +178,7 @@ def __init__( prompts: str | None = None, verify_file: str | None = None, routes_file: str | None = None, + source_files: tuple[str, ...] = (), ) -> None: self.sub_dir = sub_dir.strip("/") self.title = title @@ -184,9 +186,11 @@ def __init__( self.prompts = prompts self.verify_file = verify_file self.routes_file = routes_file + #: The project's own metadata files: a prompt text is looked for beside them. + self.source_files = source_files #: The owned theme, ``templates/``, the prompts directory and the verify and routes files - #: are read beside the model (ADR-0064), and so is the metadata directory - #: (``reads_metadata_dir``): editing one regenerates. The hash manifest is not an input: + #: are read beside the model (ADR-0064), and so is each prompt text the model names + #: (``model_inputs``): editing one regenerates. The hash manifest is not an input: #: the files the site lists are this run's and the manifest's, and the whole-run skip #: already re-runs when the manifest gains, loses or changes a file. self.declared_extra_inputs: tuple[str, ...] = tuple( @@ -213,7 +217,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: view, self.title if self.title is not None else ((project.name if known else "") or "Metadata"), self.stamp, - read_prompt_texts(view, self._prompt_dirs(root, project, known)), + read_prompt_texts(view, self._prompt_dirs(project, known)), owned / "assets" if known and (owned / "assets").is_dir() else None, owned / "templates" if known and (owned / "templates").is_dir() else None, ) @@ -241,14 +245,26 @@ def _provenance(ctx: GenContext) -> dict[str, Any] | None: out[path] = {"generatedBy": entry.get("generatedBy", ""), "sourceNode": entry["sourceNode"]} return out if raw else None - def _prompt_dirs(self, root: Any, project: Path, config_known: bool = True) -> list[Path]: - """Where prompt ``.mustache`` sources are looked for: the directories the model was - loaded from, the project's ``templates/`` and the ``prompts`` directory, each once.""" + def model_inputs(self, root: Any, project_root: Path) -> list[Path]: + """Every path a prompt's ``@textRef`` may be read from, in every directory searched.""" + dirs = self._prompt_dirs(project_root.resolve()) + files: set[Path] = set() + stack = [root] + while stack: + node = stack.pop() + ref = node.attrs().get(TEMPLATE_ATTR_TEXT_REF) + if isinstance(ref, str): + files.update(_prompt_candidates(ref, dirs)) + stack.extend(node.children()) + return sorted(files) + + def _prompt_dirs(self, project: Path, config_known: bool = True) -> list[Path]: + """Where prompt ``.mustache`` sources are looked for: the directories the project's own + metadata files are in, the project's ``templates/`` and the ``prompts`` directory, each + once.""" dirs: dict[Path, None] = {} - for node in root.children(): - for f in getattr(node.source, "files", ()) or (): - parent = Path(f).resolve().parent - dirs.setdefault(parent, None) + for f in self.source_files: + dirs.setdefault(Path(f).resolve().parent, None) templates = project / "templates" if config_known and templates.is_dir(): dirs.setdefault(templates, None) diff --git a/server/python/tests/test_gen_skip_conformance.py b/server/python/tests/test_gen_skip_conformance.py index e78d9ed3ba..7f3bf73044 100644 --- a/server/python/tests/test_gen_skip_conformance.py +++ b/server/python/tests/test_gen_skip_conformance.py @@ -447,23 +447,36 @@ def test_a_run_that_names_entities_renders_and_leaves_the_full_run_key_alone( } -def test_editing_a_prompt_in_templates_regenerates_the_docs_site( - tmp_path: Path, monkeypatch, capsys +@pytest.mark.parametrize("case", ["metaobjects", "templates", "root-file"]) +def test_an_unchanged_run_skips_and_an_edited_prompt_regenerates_the_docs_site( + case: str, tmp_path: Path, monkeypatch, capsys ) -> None: + # A prompt beside the metadata, in `templates/`, or beside a model file at the project root. project = _project(tmp_path) - (tmp_path / "metaobjects" / "meta.note.json").write_text(json.dumps(_NOTE_PROMPT)) - (tmp_path / "templates").mkdir() - prompt = tmp_path / "templates" / "note-text.mustache" + if case == "root-file": + (tmp_path / "meta.note.json").write_text(json.dumps(_NOTE_PROMPT)) + prompt = tmp_path / "note-text.mustache" + project.config.write_text( + "metadata: meta.note.json\n" + "targets:\n app:\n outDir: generated\n generators: [docs-site]\n", + encoding="utf-8", + ) + else: + (tmp_path / "metaobjects" / "meta.note.json").write_text(json.dumps(_NOTE_PROMPT)) + (tmp_path / case).mkdir(exist_ok=True) + prompt = tmp_path / case / "note-text.mustache" + project.write_config("[entity, docs-site]") prompt.write_text("first text") - project.write_config("[entity, docs-site]") h = Harness(project, monkeypatch, capsys) rc, skipped = h.gen() assert rc == 0 and not skipped, h.out + h.err model = tmp_path / "generated" / "site" / "explorer-model.js" assert "first text" in model.read_text() + rc, skipped = h.gen() + assert rc == 0 and skipped, f"{case}: nothing changed\n{h.out}{h.err}" prompt.write_text("second text") rc, skipped = h.gen() - assert rc == 0 and not skipped, "an edited prompt is an input" + assert rc == 0 and not skipped, f"{case}: an edited prompt is an input" text = model.read_text() assert "second text" in text and "first text" not in text diff --git a/server/rust/metaobjects-codegen/src/docs_site.rs b/server/rust/metaobjects-codegen/src/docs_site.rs index 9a37dbfe55..5f7d6e160d 100644 --- a/server/rust/metaobjects-codegen/src/docs_site.rs +++ b/server/rust/metaobjects-codegen/src/docs_site.rs @@ -33,10 +33,12 @@ //! `codegen/docs-site/assets/explorer.css`, `assets/explorer.js` and //! `templates/explorer-*.mustache` used in place of the shipped ones. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; +use metaobjects::collection::Collection; use metaobjects::docs_view; +use metaobjects::node::{NodeId, Tree}; use serde_json::Value; use crate::generator::{EmittedFile, GenContext, GenError, Generator, Options, unknown_options}; @@ -167,8 +169,8 @@ impl Generator for DocsSiteGenerator { true } - fn reads_source_dirs(&self) -> bool { - true + fn model_inputs(&self, tree: &Tree, root: NodeId, collection: &Collection) -> Vec { + DocsSite::default().model_inputs(tree, root, collection) } fn configure(&self, options: &Options) -> Result, GenError> { @@ -190,8 +192,8 @@ impl Generator for DocsSite { } /// The owned theme, `templates/`, the prompts directory and the verify and routes files are - /// read beside the model (ADR-0064), and so are the metadata directories - /// ([`Generator::reads_source_dirs`]): editing one regenerates. The hash manifest is not an + /// read beside the model (ADR-0064), and so is each prompt text the model names + /// ([`Generator::model_inputs`]): editing one regenerates. The hash manifest is not an /// input here: the whole-run skip already re-runs when a recorded file changes or goes. fn extra_inputs(&self) -> Vec { let mut inputs = vec![OWNED_DOCS_SITE_DIR.to_string(), TEMPLATES_DIR.to_string()]; @@ -205,8 +207,18 @@ impl Generator for DocsSite { true } - fn reads_source_dirs(&self) -> bool { - true + /// Every path a prompt's `@textRef` may be read from, in every directory searched. + fn model_inputs(&self, tree: &Tree, root: NodeId, collection: &Collection) -> Vec { + let dirs = self.prompt_dirs(collection); + let mut files = BTreeSet::new(); + let mut stack = vec![root]; + while let Some(id) = stack.pop() { + if let Some(r) = tree.attr(id, ATTR_TEXT_REF).and_then(Value::as_str) { + files.extend(prompt_candidates(r, &dirs).into_iter().flatten()); + } + stack.extend(tree.children(id).iter().copied()); + } + files.into_iter().collect() } fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { @@ -245,7 +257,7 @@ impl Generator for DocsSite { |n| n.to_string_lossy().into_owned(), ) }); - let texts = read_prompt_texts(&view, &self.prompt_dirs(ctx)); + let texts = read_prompt_texts(&view, &self.prompt_dirs(ctx.collection)); let site = emit(&SiteInput { view: &view, title: &title, @@ -293,16 +305,20 @@ impl DocsSite { /// Where prompt `.mustache` sources are looked for: the directories the model was loaded /// from, the project's `templates/` and the `prompts` directory, each once. - fn prompt_dirs(&self, ctx: &GenContext<'_>) -> Vec { - let project = &ctx.collection.config_dir; + fn prompt_dirs(&self, collection: &Collection) -> Vec { + let project = &collection.config_dir; let mut dirs: Vec = Vec::new(); let mut add = |d: PathBuf| { if d.is_dir() && !dirs.contains(&d) { dirs.push(d); } }; - for dir in crate::generator::source_dirs(&ctx.collection.source_roots) { - add(dir); + for root in &collection.source_roots { + add(if root.is_dir() { + root.clone() + } else { + root.parent().map(Path::to_path_buf).unwrap_or_default() + }); } add(project.join(TEMPLATES_DIR)); if let Some(p) = &self.prompts { @@ -431,26 +447,10 @@ pub fn read_prompt_texts(view: &Value, dirs: &[PathBuf]) -> BTreeMap = r.split(['/', '\\']).collect(); - let unsafe_ref = Path::new(r).is_absolute() - || r.starts_with('/') - || r.starts_with('\\') - || segments.iter().any(|s| s.is_empty() || *s == ".."); - if unsafe_ref { - continue; - } - for d in dirs { - let mut p = d.clone(); - for (i, s) in segments.iter().enumerate() { - if i == segments.len() - 1 { - p.push(format!("{s}{MUSTACHE}")); - } else { - p.push(s); - } - } + for p in candidates { if let Ok(text) = std::fs::read_to_string(&p) { if let Some(id) = n["id"].as_str() { out.insert(id.to_string(), text); @@ -461,3 +461,31 @@ pub fn read_prompt_texts(view: &Value, dirs: &[PathBuf]) -> BTreeMap/.mustache` for each of +/// `dirs`. `None` for a ref that is absolute or climbs out with `..`, which is never read. +fn prompt_candidates(r: &str, dirs: &[PathBuf]) -> Option> { + let segments: Vec<&str> = r.split(['/', '\\']).collect(); + let unsafe_ref = Path::new(r).is_absolute() + || r.starts_with('/') + || r.starts_with('\\') + || segments.iter().any(|s| s.is_empty() || *s == ".."); + if unsafe_ref { + return None; + } + Some( + dirs.iter() + .map(|d| { + let mut p = d.clone(); + for (i, s) in segments.iter().enumerate() { + if i == segments.len() - 1 { + p.push(format!("{s}{MUSTACHE}")); + } else { + p.push(s); + } + } + p + }) + .collect(), + ) +} diff --git a/server/rust/metaobjects-codegen/src/engine.rs b/server/rust/metaobjects-codegen/src/engine.rs index 0e61dd4ffc..0703d31e5a 100644 --- a/server/rust/metaobjects-codegen/src/engine.rs +++ b/server/rust/metaobjects-codegen/src/engine.rs @@ -728,12 +728,10 @@ fn prepare<'g>( let digest = hash_tree(&project_root.join(&extra)); entries.push(InputEntry::new(KIND_EXTRA, extra, digest)); } - if g.reads_source_dirs() { - for dir in crate::generator::source_dirs(&loaded.collection.source_roots) { - let name = dir.strip_prefix(&project_root).unwrap_or(&dir); - let name = name.to_string_lossy().replace('\\', "/"); - entries.push(InputEntry::new(KIND_EXTRA, name, hash_tree(&dir))); - } + for file in g.model_inputs(tree, loaded.result.root, &loaded.collection) { + let name = file.strip_prefix(&project_root).unwrap_or(&file); + let name = name.to_string_lossy().replace('\\', "/"); + entries.push(InputEntry::new(KIND_EXTRA, name, hash_file(&file))); } } // The owned generator crate, whole: the generator list is the adopter's file and may pull diff --git a/server/rust/metaobjects-codegen/src/generator.rs b/server/rust/metaobjects-codegen/src/generator.rs index bf223860ef..839943cb2d 100644 --- a/server/rust/metaobjects-codegen/src/generator.rs +++ b/server/rust/metaobjects-codegen/src/generator.rs @@ -6,7 +6,7 @@ use std::collections::BTreeSet; use std::fmt; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use metaobjects::collection::Collection; use metaobjects::node::{NodeId, Tree}; @@ -177,27 +177,12 @@ pub trait Generator { false } - /// Whether this generator reads files beside the metadata, in the directories the model was - /// loaded from (prompt texts). Those directories are then part of the skip key, whole. - fn reads_source_dirs(&self) -> bool { - false + /// The files this generator reads because the loaded model names them (a prompt's + /// `@textRef` text), each one present or not. Their content is part of the skip key. + fn model_inputs(&self, _tree: &Tree, _root: NodeId, _collection: &Collection) -> Vec { + Vec::new() } /// Produce the generator's files for the loaded model. fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError>; } - -/// The directories the model was loaded from: each source root, or the directory of a root -/// that is a file. -pub(crate) fn source_dirs(roots: &[PathBuf]) -> Vec { - roots - .iter() - .map(|root| { - if root.is_dir() { - root.clone() - } else { - root.parent().map(Path::to_path_buf).unwrap_or_default() - } - }) - .collect() -} diff --git a/server/rust/metaobjects-codegen/tests/docs_site.rs b/server/rust/metaobjects-codegen/tests/docs_site.rs index d7fcd71420..74ff678152 100644 --- a/server/rust/metaobjects-codegen/tests/docs_site.rs +++ b/server/rust/metaobjects-codegen/tests/docs_site.rs @@ -219,12 +219,33 @@ fn a_run_writes_the_explorer_over_the_files_the_manifest_records() { } #[test] -fn editing_a_prompt_beside_the_metadata_or_in_templates_regenerates_the_site() { - for dir in ["metaobjects", "templates"] { - let p = Scratch::project(&format!("docs-site-prompt-{dir}"), &[]); +fn an_unchanged_run_skips_and_an_edited_prompt_regenerates_the_site() { + // (case, the `sources` path, where the prompt lives): the default metadata directory, + // `templates/`, and a model whose source is a file at the project root. + for (case, source, dir) in [ + ("metaobjects", None, "metaobjects"), + ("templates", None, "templates"), + ("root-file", Some("meta.shop.json"), ""), + ] { + let p = Scratch::project(&format!("docs-site-prompt-{case}"), &[]); copy_dir(&fixture("shop").join("project"), p.path()); std::fs::remove_dir_all(p.path().join("prompts")).unwrap(); - let prompt = format!("{dir}/shop/order-note.mustache"); + if let Some(source) = source { + std::fs::rename( + p.path().join("metaobjects/meta.shop.json"), + p.path().join("meta.shop.json"), + ) + .unwrap(); + std::fs::remove_dir_all(p.path().join("metaobjects")).unwrap(); + p.write( + ".metaobjects/config.json", + &format!(r#"{{ "schema_version": 1, "sources": [{{ "path": "{source}" }}] }}"#), + ); + } + let prompt = format!( + "{dir}{}shop/order-note.mustache", + if dir.is_empty() { "" } else { "/" } + ); p.write(&prompt, "first text"); p.write( "metaobjects.config.json", @@ -232,20 +253,25 @@ fn editing_a_prompt_beside_the_metadata_or_in_templates_regenerates_the_site() { ); let mut opts = RunOptions::new(p.path()); opts.out_dir = PathBuf::from("generated"); - run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); - assert!(p.read("generated/explorer-model.js").contains("first text")); + run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("{case}: gen failed: {e}")); + assert!( + p.read("generated/explorer-model.js").contains("first text"), + "{case}: the site carries the prompt" + ); + let again = run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("{case}: {e}")); + assert_eq!(again.outcome, Outcome::Skipped, "{case}: nothing changed"); p.write(&prompt, "second text"); - let r = run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("gen failed: {e}")); + let r = run(&opts, &shipped_generators()).unwrap_or_else(|e| panic!("{case}: {e}")); assert_ne!( r.outcome, Outcome::Skipped, - "{dir}: an edited prompt is an input" + "{case}: an edited prompt is an input" ); let model = p.read("generated/explorer-model.js"); assert!( model.contains("second text") && !model.contains("first text"), - "{dir}: the site carries the edited prompt" + "{case}: the site carries the edited prompt" ); } } From ac2a0eda8ea6a28713f6d9dfa67aa868446105ae Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 06:35:45 -0500 Subject: [PATCH 04/21] no-mistakes(document): Rust docs view docs mostly current; fixed CONFORMANCE explorer row and paragraph; --transport question left open --- docs/CONFORMANCE.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 6dbf31b04f..2ae59a0255 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -73,7 +73,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | — | | [`fixtures/writer-conformance/`](../fixtures/writer-conformance/) (ADR-0063 — the code writer generators write through) | 88 cases (31 core + 10 TypeScript + 9 Java + 12 Kotlin + 6 C# + 12 Python + 8 Rust) | ✓ (the first writer; core and TypeScript dialect) | ✓ (core and Java dialect; `JavaWriter` in `codegen-base`) | ✓ (core and Kotlin dialect; `KotlinWriter` in `codegen-kotlin`) | ✓ (core and C# dialect) | ✓ (core and Python dialect) | ✓ (core and Rust dialect) | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 22 cases (17 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | — | -| [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the docs view: a loaded project + the verify payload, manifest and routes in, one `explorer.json` out) | 3 cases (`shop`, `crm`, `model-alone`) | ✓ | ✓ (`DocsView`, and the `docs-site` generator end to end) | ✓ (the JVM builder, through `codegen-kotlin`'s `docs-site`) | ✓ (`MetaObjects.DocsView`, and the `docs-site` generator end to end) | ✓ (`metaobjects.docs_view`, and the `docs-site` generator end to end) | — | +| [`fixtures/explorer-conformance/`](../fixtures/explorer-conformance/) (the docs view: a loaded project + the verify payload, manifest and routes in, one `explorer.json` out) | 3 cases (`shop`, `crm`, `model-alone`) | ✓ | ✓ (`DocsView`, and the `docs-site` generator end to end) | ✓ (the JVM builder, through `codegen-kotlin`'s `docs-site`) | ✓ (`MetaObjects.DocsView`, and the `docs-site` generator end to end) | ✓ (`metaobjects.docs_view`, and the `docs-site` generator end to end) | ✓ (`metaobjects::docs_view`, and the `docs-site` generator end to end) | **Rust (ADR-0065)** joined the table with its service stack. Its ledgers (the metamodel corpus's `server/rust/metaobjects/tests/conformance-expected-failures.json`, empty; the YAML @@ -916,7 +916,8 @@ Java (`metadata`'s `DocsViewConformanceTest`, and `codegen-base`'s `ExplorerSite generator) and Kotlin (`KotlinDocsSiteConformanceTest`, through its registry's `docs-site`) build every case byte for byte; the JVM has one builder, which Kotlin calls rather than re-implements. C# (`MetaObjects.DocsView`, through `DocsSiteGenerator` and `MetaEndpoint.MetaDocs`) and Python -(`metaobjects.docs_view`, through `docs-site` and `meta_docs`) build every case byte for byte too. +(`metaobjects.docs_view`, through `docs-site` and `meta_docs`) build every case byte for byte too; and Rust +(`metaobjects::docs_view`, through `docs-site` and `meta_endpoint::docs`) does too. **TypeScript runs it** in `server/typescript/packages/metadata/test/docs-view-conformance.test.ts` (the view) and From 229e46161082912a85fbcd0a0719025c21fcc6ab Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 06:52:55 -0500 Subject: [PATCH 05/21] wip: docs view storage section, agent pages from the view (TS reference), always-on pointer --- .../files/527e422aeec9a36d.md | 7 + agent-context-shipped/manifest.json | 1 + .../templates/agent-pages.md.mustache | 7 + fixtures/agent-pages-pointer/README.md | 20 + .../agent-pages-pointer/cases/no-hashes/.keep | 0 .../cases/no-hashes/expected-section.md | 0 .../.metaobjects/.gen-state/.hashes/shop.json | 4 + .../cases/none/expected-section.md | 0 .../.gen-state/.hashes/.root.json | 6 + .../.metaobjects/.gen-state/.hashes/shop.json | 12 + .../cases/wired/expected-section.md | 10 + .../{requirements.md.json => ledger.md.json} | 18 +- .../expected/requirements.md | 72 ---- .../{requirements.md.json => ledger.md.json} | 4 +- .../ledger-unclaimed/expected/requirements.md | 11 - .../explorer-conformance/crm/expected.json | 170 +++++++- .../model-alone/expected.json | 155 ++++++- .../explorer-conformance/shop/expected.json | 304 +++++++++++++- .../registry.json | 10 +- scripts/ci-local.sh | 6 + scripts/sync-doc-templates.sh | 36 +- .../Templates/agent/requirements.md.mustache | 34 ++ .../Templates/agent/schema.md.mustache | 123 ++++++ .../requirements/requirements.md.mustache | 27 ++ .../requirements/requirements.toon.mustache | 2 + .../templates/agent/requirements.md.mustache | 34 ++ .../templates/agent/schema.md.mustache | 123 ++++++ .../requirements/requirements.md.mustache | 27 ++ .../requirements/requirements.toon.mustache | 2 + .../shipped/files/527e422aeec9a36d.md | 7 + .../agent_context/shipped/manifest.json | 1 + .../templates/agent/requirements.md.mustache | 34 ++ .../templates/agent/schema.md.mustache | 123 ++++++ .../requirements/requirements.md.mustache | 27 ++ .../requirements/requirements.toon.mustache | 2 + .../packages/cli/src/commands/init.ts | 10 +- .../cli/test/docs-page-conformance.test.ts | 32 +- .../packages/codegen-ts/src/docs-view-run.ts | 7 +- .../src/generators/agent-requirements-page.ts | 85 +--- .../src/generators/api-docs-file.ts | 13 +- .../src/generators/docs-view-pages.ts | 386 ++++++++++++++++++ .../src/generators/requirements-file.ts | 14 +- .../src/generators/requirements-view.ts | 61 +-- .../packages/codegen-ts/src/index.ts | 15 + .../codegen-ts/src/reference/requirements.ts | 29 +- .../packages/metadata/src/docs-view/build.ts | 9 + .../metadata/src/docs-view/storage.ts | 334 +++++++++++++++ .../packages/metadata/src/docs-view/types.ts | 88 ++++ .../sdk/src/agent-context/agent-pages.ts | 66 +++ .../sdk/src/agent-context/assemble.ts | 5 +- .../packages/sdk/src/agent-context/index.ts | 1 + .../packages/sdk/src/agent-context/shipped.ts | 11 + .../test/agent-context/agent-pages.test.ts | 36 ++ .../sdk/test/agent-context/shipped.test.ts | 2 +- 54 files changed, 2338 insertions(+), 285 deletions(-) create mode 100644 agent-context-shipped/files/527e422aeec9a36d.md create mode 100644 agent-context/templates/agent-pages.md.mustache create mode 100644 fixtures/agent-pages-pointer/README.md create mode 100644 fixtures/agent-pages-pointer/cases/no-hashes/.keep create mode 100644 fixtures/agent-pages-pointer/cases/no-hashes/expected-section.md create mode 100644 fixtures/agent-pages-pointer/cases/none/.metaobjects/.gen-state/.hashes/shop.json create mode 100644 fixtures/agent-pages-pointer/cases/none/expected-section.md create mode 100644 fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/.root.json create mode 100644 fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/shop.json create mode 100644 fixtures/agent-pages-pointer/cases/wired/expected-section.md rename fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/{requirements.md.json => ledger.md.json} (79%) delete mode 100644 fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.md rename fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/{requirements.md.json => ledger.md.json} (82%) delete mode 100644 fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.md create mode 100644 server/csharp/MetaObjects.Codegen/Templates/agent/requirements.md.mustache create mode 100644 server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache create mode 100644 server/csharp/MetaObjects.Codegen/Templates/requirements/requirements.md.mustache create mode 100644 server/csharp/MetaObjects.Codegen/Templates/requirements/requirements.toon.mustache create mode 100644 server/java/codegen-base/src/main/resources/metaobjects/templates/agent/requirements.md.mustache create mode 100644 server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache create mode 100644 server/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.md.mustache create mode 100644 server/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.toon.mustache create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/527e422aeec9a36d.md create mode 100644 server/rust/metaobjects-codegen/templates/agent/requirements.md.mustache create mode 100644 server/rust/metaobjects-codegen/templates/agent/schema.md.mustache create mode 100644 server/rust/metaobjects-codegen/templates/requirements/requirements.md.mustache create mode 100644 server/rust/metaobjects-codegen/templates/requirements/requirements.toon.mustache create mode 100644 server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts create mode 100644 server/typescript/packages/metadata/src/docs-view/storage.ts create mode 100644 server/typescript/packages/sdk/src/agent-context/agent-pages.ts create mode 100644 server/typescript/packages/sdk/test/agent-context/agent-pages.test.ts diff --git a/agent-context-shipped/files/527e422aeec9a36d.md b/agent-context-shipped/files/527e422aeec9a36d.md new file mode 100644 index 0000000000..579a3509ae --- /dev/null +++ b/agent-context-shipped/files/527e422aeec9a36d.md @@ -0,0 +1,7 @@ +## Pages generated for this project + +`meta gen` writes these from the metadata (they are regenerated output, like the code). Read the +one for a tier before you change that tier: + +{{pageList}} + diff --git a/agent-context-shipped/manifest.json b/agent-context-shipped/manifest.json index dd3daf5969..bf05f04901 100644 --- a/agent-context-shipped/manifest.json +++ b/agent-context-shipped/manifest.json @@ -3,6 +3,7 @@ "docsRef": "main", "docsLinkPrefix": "https://github.com/metaobjectsdev/metaobjects/blob/", "skillsDir": ".claude/skills", + "agentPagesTemplate": "527e422aeec9a36d.md", "stacks": [ { "id": "typescript", diff --git a/agent-context/templates/agent-pages.md.mustache b/agent-context/templates/agent-pages.md.mustache new file mode 100644 index 0000000000..579a3509ae --- /dev/null +++ b/agent-context/templates/agent-pages.md.mustache @@ -0,0 +1,7 @@ +## Pages generated for this project + +`meta gen` writes these from the metadata (they are regenerated output, like the code). Read the +one for a tier before you change that tier: + +{{pageList}} + diff --git a/fixtures/agent-pages-pointer/README.md b/fixtures/agent-pages-pointer/README.md new file mode 100644 index 0000000000..77f9e43b4d --- /dev/null +++ b/fixtures/agent-pages-pointer/README.md @@ -0,0 +1,20 @@ +# agent-pages-pointer + +The always-on agent file (`.metaobjects/AGENTS.md`) points at the pages `meta gen` writes for a +coding agent (`agent/schema.md`, `agent/ui.md`, `agent/requirements.md`, `AGENT-API.md`, +`requirements.toon`) only when the project's last `gen` wrote one. Every port that scaffolds the +always-on file reads what was written from the committed `.metaobjects/.gen-state/.hashes/` +(one JSON file per package, keyed by project-relative path; a value is a hash or an object +carrying one), renders the section from the template the shipped manifest names +(`agentPagesTemplate`, from `agent-context/templates/agent-pages.md.mustache`), and inserts it +above the file's `## Rules` heading. + +Each case is a project root. `expected-section.md` is the rendered section: empty when no page +is wired, which leaves the always-on file exactly as shipped. + +- `no-hashes`: no `.hashes/` directory at all. +- `none`: hashes record generated code and per-object pages, but no agent page. +- `wired`: four agent pages over two hashes files in the two value shapes, plus a near miss + (`schema.md.orig`) that is not one. Pages list in the fixed page order, then by path. + +The reference is `server/typescript/packages/sdk/src/agent-context/agent-pages.ts`. diff --git a/fixtures/agent-pages-pointer/cases/no-hashes/.keep b/fixtures/agent-pages-pointer/cases/no-hashes/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/fixtures/agent-pages-pointer/cases/no-hashes/expected-section.md b/fixtures/agent-pages-pointer/cases/no-hashes/expected-section.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/fixtures/agent-pages-pointer/cases/none/.metaobjects/.gen-state/.hashes/shop.json b/fixtures/agent-pages-pointer/cases/none/.metaobjects/.gen-state/.hashes/shop.json new file mode 100644 index 0000000000..4d0d37d055 --- /dev/null +++ b/fixtures/agent-pages-pointer/cases/none/.metaobjects/.gen-state/.hashes/shop.json @@ -0,0 +1,4 @@ +{ + "src/generated/shop/Order.ts": "0000000000000000000000000000000000000000000000000000000000000000", + "docs/shop/Order.md": "1111111111111111111111111111111111111111111111111111111111111111" +} diff --git a/fixtures/agent-pages-pointer/cases/none/expected-section.md b/fixtures/agent-pages-pointer/cases/none/expected-section.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/.root.json b/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/.root.json new file mode 100644 index 0000000000..f019e1ea55 --- /dev/null +++ b/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/.root.json @@ -0,0 +1,6 @@ +{ + "docs/requirements.toon": "2222222222222222222222222222222222222222222222222222222222222222", + "docs/agent/requirements.md": "3333333333333333333333333333333333333333333333333333333333333333", + "docs/agent/schema.md": "4444444444444444444444444444444444444444444444444444444444444444", + "docs/agent/schema.md.orig": "5555555555555555555555555555555555555555555555555555555555555555" +} diff --git a/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/shop.json b/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/shop.json new file mode 100644 index 0000000000..5c5640c622 --- /dev/null +++ b/fixtures/agent-pages-pointer/cases/wired/.metaobjects/.gen-state/.hashes/shop.json @@ -0,0 +1,12 @@ +{ + "docs/api/AGENT-API.md": { + "hash": "6666666666666666666666666666666666666666666666666666666666666666", + "generatedBy": "api-docs", + "sourceNode": "shop" + }, + "generated/shop/src/order.rs": { + "hash": "7777777777777777777777777777777777777777777777777777777777777777", + "generatedBy": "entity", + "sourceNode": "shop::Order" + } +} diff --git a/fixtures/agent-pages-pointer/cases/wired/expected-section.md b/fixtures/agent-pages-pointer/cases/wired/expected-section.md new file mode 100644 index 0000000000..3926fbfc18 --- /dev/null +++ b/fixtures/agent-pages-pointer/cases/wired/expected-section.md @@ -0,0 +1,10 @@ +## Pages generated for this project + +`meta gen` writes these from the metadata (they are regenerated output, like the code). Read the +one for a tier before you change that tier: + +- `docs/agent/schema.md`: before you touch persistence: tables, columns, keys and views. +- `docs/agent/requirements.md`: before you add or change a capability. +- `docs/api/AGENT-API.md`: before you call or change the generated API. +- `docs/requirements.toon`: the requirement ledger, in the form a tool reads. + diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.md.json b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/ledger.md.json similarity index 79% rename from fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.md.json rename to fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/ledger.md.json index 2e53f21d77..ade04705f3 100644 --- a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/requirements.md.json +++ b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/data/ledger.md.json @@ -1,50 +1,50 @@ { - "embedded": false, + "embedded": true, "count": 7, "plural": "s", "entries": [ { - "heading": "## Storefront", + "heading": "### Storefront", "facts": "`functional` · **L1** · status: `live`", "statement": "The storefront solution", "counterexample": "**Counterexample:** Nothing can be sold" }, { - "heading": "### Storefront.OrderService", + "heading": "#### Storefront.OrderService", "facts": "`functional` · **L3** · status: `live`", "statement": "Every placed order is recorded before payment is attempted", "counterexample": "**Counterexample:** A payment attempted against an order that was never stored", - "description": "Recording first is what lets a failed payment be retried.\n\n# Why first\n\nA payment with no order is a refund nobody can trace." + "description": "Recording first is what lets a failed payment be retried.\n\n## Why first\n\nA payment with no order is a refund nobody can trace." }, { - "heading": "#### Storefront.OrderService.OrderRecord — What an order must hold", + "heading": "##### Storefront.OrderService.OrderRecord — What an order must hold", "facts": "`functional` · **L4** · status: `live`", "statement": "An order records what was bought, for how much, and when: placed | paid", "counterexample": "**Counterexample:** An order row that cannot say who placed it", "implementedBy": "**Implemented by:** `acme::shop::Order`, `acme::shop::Order.placedAt`" }, { - "heading": "##### Storefront.OrderService.OrderRecord.TranscribableReference", + "heading": "###### Storefront.OrderService.OrderRecord.TranscribableReference", "facts": "`functional` · **L5** · status: `live`", "statement": "An order carries a reference a customer can read\ndown a phone line", "counterexample": "**Counterexample:** A reference that is a raw uuid", "implementedBy": "**Implemented by:** `acme::shop::Order.reference`" }, { - "heading": "##### Storefront.OrderService.OrderRecord.OrderExpiry", + "heading": "###### Storefront.OrderService.OrderRecord.OrderExpiry", "facts": "`functional` · **L5** · status: `planned` · tracked: acme/shop#412", "statement": "An unpaid order carries the instant it stops being reservable", "counterexample": "**Counterexample:** Stock held indefinitely against an order nobody paid for" }, { - "heading": "## MoneyIsExactMinorUnits", + "heading": "### MoneyIsExactMinorUnits", "facts": "`architectural` · status: `live`", "statement": "Monetary amounts are stored as exact integer minor units, never as floating point", "counterexample": "**Counterexample:** A cent that disappears when a total is split three ways", "implementedBy": "**Implemented by:** `acme::shop::Invoice`" }, { - "heading": "## GuestCheckout", + "heading": "### GuestCheckout", "facts": "`functional` · **L4** · status: `retired`", "statement": "A visitor can check out without an account", "counterexample": "**Counterexample:** An order with no way to reach the person who placed it" diff --git a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.md b/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.md deleted file mode 100644 index 799e1ed6b7..0000000000 --- a/fixtures/docs-page-conformance/cases/ledger-and-claims/expected/requirements.md +++ /dev/null @@ -1,72 +0,0 @@ -# Requirements - -7 declared requirements, in declaration order. - -## Storefront - -`functional` · **L1** · status: `live` - -The storefront solution - -**Counterexample:** Nothing can be sold - -### Storefront.OrderService - -`functional` · **L3** · status: `live` - -Every placed order is recorded before payment is attempted - -**Counterexample:** A payment attempted against an order that was never stored - -Recording first is what lets a failed payment be retried. - -# Why first - -A payment with no order is a refund nobody can trace. - -#### Storefront.OrderService.OrderRecord — What an order must hold - -`functional` · **L4** · status: `live` - -An order records what was bought, for how much, and when: placed | paid - -**Counterexample:** An order row that cannot say who placed it - -**Implemented by:** `acme::shop::Order`, `acme::shop::Order.placedAt` - -##### Storefront.OrderService.OrderRecord.TranscribableReference - -`functional` · **L5** · status: `live` - -An order carries a reference a customer can read -down a phone line - -**Counterexample:** A reference that is a raw uuid - -**Implemented by:** `acme::shop::Order.reference` - -##### Storefront.OrderService.OrderRecord.OrderExpiry - -`functional` · **L5** · status: `planned` · tracked: acme/shop#412 - -An unpaid order carries the instant it stops being reservable - -**Counterexample:** Stock held indefinitely against an order nobody paid for - -## MoneyIsExactMinorUnits - -`architectural` · status: `live` - -Monetary amounts are stored as exact integer minor units, never as floating point - -**Counterexample:** A cent that disappears when a total is split three ways - -**Implemented by:** `acme::shop::Invoice` - -## GuestCheckout - -`functional` · **L4** · status: `retired` - -A visitor can check out without an account - -**Counterexample:** An order with no way to reach the person who placed it diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.md.json b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/ledger.md.json similarity index 82% rename from fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.md.json rename to fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/ledger.md.json index 9764aa2e2e..0b0c4db57c 100644 --- a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/requirements.md.json +++ b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/data/ledger.md.json @@ -1,10 +1,10 @@ { - "embedded": false, + "embedded": true, "count": 1, "plural": "", "entries": [ { - "heading": "## ExportsAreResumable", + "heading": "### ExportsAreResumable", "facts": "`functional` · **L4** · status: `planned` · disposition: `deferred`", "statement": "true", "counterexample": "**Counterexample:** A 2 GB export that restarts from zero after a dropped connection" diff --git a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.md b/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.md deleted file mode 100644 index eec567a3ae..0000000000 --- a/fixtures/docs-page-conformance/cases/ledger-unclaimed/expected/requirements.md +++ /dev/null @@ -1,11 +0,0 @@ -# Requirements - -1 declared requirement, in declaration order. - -## ExportsAreResumable - -`functional` · **L4** · status: `planned` · disposition: `deferred` - -true - -**Counterexample:** A 2 GB export that restarts from zero after a dropped connection diff --git a/fixtures/explorer-conformance/crm/expected.json b/fixtures/explorer-conformance/crm/expected.json index 21e857bf28..0fa73a3f0f 100644 --- a/fixtures/explorer-conformance/crm/expected.json +++ b/fixtures/explorer-conformance/crm/expected.json @@ -2229,5 +2229,173 @@ "acme::tax::tax" ] } - ] + ], + "storage": { + "physical": false, + "dialect": "", + "tables": [ + { + "name": "accounts", + "schema": "", + "declaredBy": { + "label": "Account", + "id": "acme::crm::Account", + "path": "model/acme/crm/Account.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Account", + "id": "acme::crm::Account", + "path": "model/acme/crm/Account.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "Account.id", + "id": "acme::crm::Account.id", + "path": "model/acme/crm/Account.html#m-id", + "kind": "field.long", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "name", + "field": { + "label": "Account.name", + "id": "acme::crm::Account.name", + "path": "model/acme/crm/Account.html#m-name", + "kind": "field.string", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [], + "indexes": null, + "checks": null + }, + { + "name": "leads", + "schema": "", + "declaredBy": { + "label": "Lead", + "id": "acme::crm::Lead", + "path": "model/acme/crm/Lead.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Lead", + "id": "acme::crm::Lead", + "path": "model/acme/crm/Lead.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "A prospective customer.", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "score", + "field": { + "label": "Lead.score", + "id": "acme::crm::Lead.score", + "path": "model/acme/crm/Lead.html#m-score", + "kind": "field.long", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "id", + "field": { + "label": "Lead.id", + "id": "acme::crm::Lead.id", + "path": "model/acme/crm/Lead.html#m-id", + "kind": "field.long", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "email", + "field": { + "label": "Lead.email", + "id": "acme::crm::Lead.email", + "path": "model/acme/crm/Lead.html#m-email", + "kind": "field.string", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "account_id", + "field": { + "label": "Lead.accountId", + "id": "acme::crm::Lead.accountId", + "path": "model/acme/crm/Lead.html#m-accountId", + "kind": "field.long", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [ + { + "columns": [ + "account_id" + ], + "refTable": "accounts", + "refColumns": [ + "id" + ], + "name": null, + "onDelete": null, + "onUpdate": null + } + ], + "indexes": null, + "checks": null + } + ], + "views": [] + } } diff --git a/fixtures/explorer-conformance/model-alone/expected.json b/fixtures/explorer-conformance/model-alone/expected.json index 84ff4ef38a..d9c9265bcd 100644 --- a/fixtures/explorer-conformance/model-alone/expected.json +++ b/fixtures/explorer-conformance/model-alone/expected.json @@ -702,5 +702,158 @@ "acme::library::Book" ] } - ] + ], + "storage": { + "physical": false, + "dialect": "", + "tables": [ + { + "name": "authors", + "schema": "", + "declaredBy": { + "label": "Author", + "id": "acme::library::Author", + "path": "model/acme/library/Author.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Author", + "id": "acme::library::Author", + "path": "model/acme/library/Author.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "Author.id", + "id": "acme::library::Author.id", + "path": "model/acme/library/Author.html#m-id", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "name", + "field": { + "label": "Author.name", + "id": "acme::library::Author.name", + "path": "model/acme/library/Author.html#m-name", + "kind": "field.string", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [], + "indexes": null, + "checks": null + }, + { + "name": "books", + "schema": "", + "declaredBy": { + "label": "Book", + "id": "acme::library::Book", + "path": "model/acme/library/Book.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Book", + "id": "acme::library::Book", + "path": "model/acme/library/Book.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "Book.id", + "id": "acme::library::Book.id", + "path": "model/acme/library/Book.html#m-id", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "title", + "field": { + "label": "Book.title", + "id": "acme::library::Book.title", + "path": "model/acme/library/Book.html#m-title", + "kind": "field.string", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "author_id", + "field": { + "label": "Book.authorId", + "id": "acme::library::Book.authorId", + "path": "model/acme/library/Book.html#m-authorId", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [ + { + "columns": [ + "author_id" + ], + "refTable": "authors", + "refColumns": [ + "id" + ], + "name": null, + "onDelete": null, + "onUpdate": null + } + ], + "indexes": null, + "checks": null + } + ], + "views": [] + } } diff --git a/fixtures/explorer-conformance/shop/expected.json b/fixtures/explorer-conformance/shop/expected.json index 6c055ef32b..e2120e111b 100644 --- a/fixtures/explorer-conformance/shop/expected.json +++ b/fixtures/explorer-conformance/shop/expected.json @@ -3277,5 +3277,307 @@ "acme::shop::Shop.Checkout.Orders.Recorded.Quotable" ] } - ] + ], + "storage": { + "physical": false, + "dialect": "", + "tables": [ + { + "name": "audit_entries", + "schema": "", + "declaredBy": { + "label": "AuditEntry", + "id": "acme::shop::AuditEntry", + "path": "model/acme/shop/AuditEntry.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "AuditEntry", + "id": "acme::shop::AuditEntry", + "path": "model/acme/shop/AuditEntry.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "AuditEntry.id", + "id": "acme::shop::AuditEntry.id", + "path": "model/acme/shop/AuditEntry.html#m-id", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "message", + "field": { + "label": "AuditEntry.message", + "id": "acme::shop::AuditEntry.message", + "path": "model/acme/shop/AuditEntry.html#m-message", + "kind": "field.string", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [], + "indexes": null, + "checks": null + }, + { + "name": "customers", + "schema": "", + "declaredBy": { + "label": "Customer", + "id": "acme::shop::Customer", + "path": "model/acme/shop/Customer.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Customer", + "id": "acme::shop::Customer", + "path": "model/acme/shop/Customer.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "Customer.id", + "id": "acme::shop::Customer.id", + "path": "model/acme/shop/Customer.html#m-id", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "created_at", + "field": { + "label": "Customer.createdAt", + "id": "acme::shop::Customer.createdAt", + "path": "model/acme/shop/Customer.html#m-createdAt", + "kind": "field.timestamp", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "name", + "field": { + "label": "Customer.name", + "id": "acme::shop::Customer.name", + "path": "model/acme/shop/Customer.html#m-name", + "kind": "field.string", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "email", + "field": { + "label": "Customer.email", + "id": "acme::shop::Customer.email", + "path": "model/acme/shop/Customer.html#m-email", + "kind": "field.string", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "shipping_address", + "field": { + "label": "Customer.shippingAddress", + "id": "acme::shop::Customer.shippingAddress", + "path": "model/acme/shop/Customer.html#m-shippingAddress", + "kind": "field.object", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [], + "indexes": null, + "checks": null + }, + { + "name": "orders", + "schema": "", + "declaredBy": { + "label": "Order", + "id": "acme::shop::Order", + "path": "model/acme/shop/Order.html", + "kind": "object.entity", + "unresolved": false + }, + "objects": [ + { + "label": "Order", + "id": "acme::shop::Order", + "path": "model/acme/shop/Order.html", + "kind": "object.entity", + "unresolved": false + } + ], + "description": "", + "primaryKey": [ + "id" + ], + "columns": [ + { + "name": "id", + "field": { + "label": "Order.id", + "id": "acme::shop::Order.id", + "path": "model/acme/shop/Order.html#m-id", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": false, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "created_at", + "field": { + "label": "Order.createdAt", + "id": "acme::shop::Order.createdAt", + "path": "model/acme/shop/Order.html#m-createdAt", + "kind": "field.timestamp", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "customer_id", + "field": { + "label": "Order.customerId", + "id": "acme::shop::Order.customerId", + "path": "model/acme/shop/Order.html#m-customerId", + "kind": "field.uuid", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "reference", + "field": { + "label": "Order.reference", + "id": "acme::shop::Order.reference", + "path": "model/acme/shop/Order.html#m-reference", + "kind": "field.string", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "total", + "field": { + "label": "Order.total", + "id": "acme::shop::Order.total", + "path": "model/acme/shop/Order.html#m-total", + "kind": "field.decimal", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + }, + { + "name": "state", + "field": { + "label": "Order.state", + "id": "acme::shop::Order.state", + "path": "model/acme/shop/Order.html#m-state", + "kind": "field.enum", + "unresolved": false + }, + "nullable": true, + "identity": "", + "description": "", + "sqlType": null, + "default": null + } + ], + "foreignKeys": [ + { + "columns": [ + "customer_id" + ], + "refTable": "customers", + "refColumns": [ + "id" + ], + "name": null, + "onDelete": null, + "onUpdate": null + } + ], + "indexes": null, + "checks": null + } + ], + "views": [] + } } diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index 60ddd95c80..9aaaeaaa9e 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -330,20 +330,20 @@ "ports": ["typescript"] }, "requirements": { - "concept": "The requirement ledger as documentation: requirements.md for people and requirements.toon for tools.", + "concept": "The requirement ledger as requirements.toon, for tools; people read it in the explorer (docs-site).", "tier": "neutral", "layer": "docs", - "note": "Listed like any generator; writes to the `docs` target (ADR-0034 Amendment 9). A project that declares no requirement.* node gets no file.", + "note": "Listed like any generator; writes to the `docs` target (ADR-0034 Amendment 9). A project that declares no requirement.* node gets no file. Every port renders the shared templates/requirements/ Mustache page over its docs view, gated by fixtures/docs-page-conformance/; the human requirements.md page was retired in 1.3.0.", "eject": "full", - "ports": ["typescript", "python"] + "ports": ["typescript", "csharp", "java", "kotlin", "python", "rust"] }, "agent-docs": { "concept": "Pages written for a coding agent working in the project: the schema, the UI surface and the requirements.", "tier": "neutral", "layer": "docs", - "note": "Listed like any generator; writes to the `docs` target (ADR-0034 Amendment 9).", + "note": "Listed like any generator; writes to the `docs` target (ADR-0034 Amendment 9). Every port renders agent/requirements.md and the model-only agent/schema.md from the shared templates/agent/ Mustache pages over its docs view, gated by fixtures/docs-page-conformance/; agent/ui.md and the physical schema (SQL types, defaults, indexes) are TypeScript's.", "eject": "full", - "ports": ["typescript", "python"] + "ports": ["typescript", "csharp", "java", "kotlin", "python", "rust"] }, "metamodel-docs": { "concept": "The reference of the built-in metamodel: every type, subtype and attribute the build registers, by provider.", diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 84a880812c..817784948d 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -1110,8 +1110,14 @@ gate_doc_template_drift() { server/typescript/packages/codegen-ts/templates server/typescript/packages/codegen-ts/src/render-engine/embedded-templates.generated.ts server/python/src/metaobjects/render/bundled_templates + server/csharp/MetaObjects.Codegen/Templates/requirements + server/csharp/MetaObjects.Codegen/Templates/agent server/csharp/MetaObjects.Codegen/Templates/metamodel + server/java/codegen-base/src/main/resources/metaobjects/templates/requirements + server/java/codegen-base/src/main/resources/metaobjects/templates/agent server/java/codegen-base/src/main/resources/metaobjects/templates/metamodel + server/rust/metaobjects-codegen/templates/requirements + server/rust/metaobjects-codegen/templates/agent server/rust/metaobjects-codegen/templates/metamodel ) bash scripts/sync-doc-templates.sh || return 1 diff --git a/scripts/sync-doc-templates.sh b/scripts/sync-doc-templates.sh index a215f6c1c2..90070ad31a 100755 --- a/scripts/sync-doc-templates.sh +++ b/scripts/sync-doc-templates.sh @@ -39,13 +39,16 @@ DEST_ROOTS=( PYTHON_DEST_ROOT="${REPO_ROOT}/server/python/src/metaobjects/render/bundled_templates" PYTHON_GROUPS=(requirements agent metamodel) -# The metamodel reference pages (the metamodel-docs generator) render in every port, so -# the metamodel group also ships in the C#, JVM (Java and Kotlin) and Rust packages. The -# group carries one data file beside its templates, provider-descriptions.json. -METAMODEL_EXTRA_DESTS=( - "${REPO_ROOT}/server/csharp/MetaObjects.Codegen/Templates/metamodel" - "${REPO_ROOT}/server/java/codegen-base/src/main/resources/metaobjects/templates/metamodel" - "${REPO_ROOT}/server/rust/metaobjects-codegen/templates/metamodel" +# The metamodel reference pages (the metamodel-docs generator) and the agent pages +# (requirements.toon, agent/requirements.md, the model-only agent/schema.md) render in every +# port, so those groups also ship in the C#, JVM (Java and Kotlin) and Rust packages, each +# under /. The metamodel group carries one data file beside its templates, +# provider-descriptions.json. +PORT_GROUPS=(requirements agent metamodel) +PORT_DEST_ROOTS=( + "${REPO_ROOT}/server/csharp/MetaObjects.Codegen/Templates" + "${REPO_ROOT}/server/java/codegen-base/src/main/resources/metaobjects/templates" + "${REPO_ROOT}/server/rust/metaobjects-codegen/templates" ) for group in "${TEMPLATE_GROUPS[@]}"; do @@ -74,15 +77,18 @@ for group in "${TEMPLATE_GROUPS[@]}"; do done done - if [[ "${group}" == "metamodel" ]]; then - for dest in "${METAMODEL_EXTRA_DESTS[@]}"; do - mkdir -p "${dest}" - for src in "${src_files[@]}"; do - cp "${src}" "${dest}/$(basename "${src}")" - echo "synced: ${src} -> ${dest}/$(basename "${src}")" + for port_group in "${PORT_GROUPS[@]}"; do + if [[ "${port_group}" == "${group}" ]]; then + for dest_root in "${PORT_DEST_ROOTS[@]}"; do + dest="${dest_root}/${group}" + mkdir -p "${dest}" + for src in "${src_files[@]}"; do + cp "${src}" "${dest}/$(basename "${src}")" + echo "synced: ${src} -> ${dest}/$(basename "${src}")" + done done - done - fi + fi + done for py_group in "${PYTHON_GROUPS[@]}"; do if [[ "${py_group}" == "${group}" ]]; then diff --git a/server/csharp/MetaObjects.Codegen/Templates/agent/requirements.md.mustache b/server/csharp/MetaObjects.Codegen/Templates/agent/requirements.md.mustache new file mode 100644 index 0000000000..cb7cba06cb --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Templates/agent/requirements.md.mustache @@ -0,0 +1,34 @@ +{{{generatedMarker}}} + +# Requirements + +Read this before adding a capability, and before extending anything that looks like it already does what you were asked for. + +- A requirement is **prescriptive**: it states what should be true, never what happened. `status: retired` means the capability was BUILT and deliberately REMOVED — that entry is a prohibition, not history, and the right response to it is to stop, not to rebuild. +- The **node index** below answers *"does anything claim the thing I am about to change?"*. Match the literal FQN. +- **The ledger under it is not the same list.** A retired capability carries no `@implementedBy` — there is nothing left to point at — so it appears there and in no index. Read it before you conclude a capability does not exist yet. + +## Node index + +{{#hasNodeIndex}} +| Node | Kind | Claimed by | +|---|---|---| +{{#nodeIndex}} +| `{{{address}}}` | `{{{concern}}}` | {{{claims}}} | +{{/nodeIndex}} +{{#hasStatements}} + +### What those requirements say + +{{#statements}} +- `{{{path}}}` (`{{{subType}}}`) — {{{statement}}} +{{/statements}} +{{/hasStatements}} +{{/hasNodeIndex}} +{{^hasNodeIndex}} +No requirement resolves to a model node. The common reason is the ordinary one: an entry at L4 or L5 that simply declares no `@implementedBy` yet, which is legal and is what a `planned` entry looks like. The others are an entry sitting ABOVE the L4 link floor (where a claim is not permitted), a `retired` entry (where it is forbidden outright), and a claim that names a node nothing resolves — `meta verify` is what says which. +{{/hasNodeIndex}} + +## The ledger + +{{{ledger}}} diff --git a/server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache b/server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache new file mode 100644 index 0000000000..ad91a93c2f --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Templates/agent/schema.md.mustache @@ -0,0 +1,123 @@ +{{{generatedMarker}}} + +# Schema + +{{#physical}} +The physical shape of the `{{{dialect}}}` database this model generates. Read it before writing a query, a migration, or anything that names a table or a column. +{{/physical}} +{{^physical}} +The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. +{{/physical}} + +- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. +{{#hasMigrate}} +- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. +{{/hasMigrate}} +{{^hasMigrate}} +- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +{{/hasMigrate}} +- `Field` and `Declared` are the METADATA names. Edit those; the column name follows. + +{{#descriptionNudge}} +> **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text {{#hasMigrate}}`meta migrate`{{/hasMigrate}}{{^hasMigrate}}`meta schema`{{/hasMigrate}} emits as a `COMMENT ON`, so it lands in the database too. + +{{/descriptionNudge}} +{{#hasTables}} +## Tables + +{{#tables}} +### {{{heading}}} + +{{#tableDeclaredBy}} +Declared by `{{{.}}}`. +{{/tableDeclaredBy}} +{{#tableDescription}} + +> {{{.}}} +{{/tableDescription}} + +{{#physical}} +| Column | Field | Declared | SQL type | Null | Default | Key | +|---|---|---|---|---|---|---| +{{/physical}} +{{^physical}} +| Column | Field | Declared | Null | Key | +|---|---|---|---|---| +{{/physical}} +{{#columns}} +| `{{{name}}}` | {{{fieldCell}}} | {{{declaredCell}}} |{{#physical}} {{{sqlTypeCell}}} |{{/physical}} {{{nullCell}}} |{{#physical}} {{{defaultCell}}} |{{/physical}} {{{keyCell}}} | +{{/columns}} +{{#hasDescribed}} + +{{#described}} +- `{{{name}}}` — {{{text}}} +{{/described}} +{{/hasDescribed}} +{{#hasIndexes}} + +**Indexes** + +{{#indexes}} +- {{{.}}} +{{/indexes}} +{{/hasIndexes}} +{{#hasForeignKeys}} + +**Foreign keys** + +{{#foreignKeys}} +- {{{.}}} +{{/foreignKeys}} +{{/hasForeignKeys}} +{{#hasChecks}} + +**Checks** + +{{#checks}} +- {{{.}}} +{{/checks}} +{{/hasChecks}} + +{{/tables}} +{{/hasTables}} +{{#hasViews}} +## Views + +A view is generated from its projection's `origin.*` children{{#hasReportView}} or its report's dimensions and measures{{/hasReportView}} — it is derived, never hand-written. Editing the view SQL directly is drift the tool cannot see. + +{{#views}} +### {{{heading}}} + +{{#viewDeclaredBy}} +Declared by `{{{.}}}`. +{{/viewDeclaredBy}} +{{#hasLineage}} + +| Column | Lineage | +|---|---| +{{#lineage}} +| `{{{column}}}` | {{{text}}} | +{{/lineage}} +{{/hasLineage}} + +{{/views}} +{{/hasViews}} +{{#hasRelationships}} +## Relationships + +{{#relationships}} +- {{{.}}} +{{/relationships}} + +{{/hasRelationships}} +{{#hasEnums}} +## Enums + +Members are the values the wire and the generated types use.{{#physical}} Whether the DATABASE also refuses a value outside the set is that table's **Checks** above — an `@isArray` enum carries none, and neither does a view column.{{/physical}} + +| Field | Members | Storage | +|---|---|---| +{{#enums}} +| `{{{field}}}` | {{{members}}} | {{{storage}}} | +{{/enums}} +{{/hasEnums}} diff --git a/server/csharp/MetaObjects.Codegen/Templates/requirements/requirements.md.mustache b/server/csharp/MetaObjects.Codegen/Templates/requirements/requirements.md.mustache new file mode 100644 index 0000000000..a200094478 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Templates/requirements/requirements.md.mustache @@ -0,0 +1,27 @@ +{{^embedded}} +# Requirements + +{{/embedded}} +{{{count}}} declared requirement{{{plural}}}, in declaration order. +{{#entries}} + +{{{heading}}} + +{{{facts}}} +{{#statement}} + +{{{.}}} +{{/statement}} +{{#counterexample}} + +{{{.}}} +{{/counterexample}} +{{#description}} + +{{{.}}} +{{/description}} +{{#implementedBy}} + +{{{.}}} +{{/implementedBy}} +{{/entries}} diff --git a/server/csharp/MetaObjects.Codegen/Templates/requirements/requirements.toon.mustache b/server/csharp/MetaObjects.Codegen/Templates/requirements/requirements.toon.mustache new file mode 100644 index 0000000000..cae64ef896 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Templates/requirements/requirements.toon.mustache @@ -0,0 +1,2 @@ +requirements[{{{count}}}]{{{fields}}}:{{#rows}} + {{{line}}}{{/rows}} \ No newline at end of file diff --git a/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/requirements.md.mustache b/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/requirements.md.mustache new file mode 100644 index 0000000000..cb7cba06cb --- /dev/null +++ b/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/requirements.md.mustache @@ -0,0 +1,34 @@ +{{{generatedMarker}}} + +# Requirements + +Read this before adding a capability, and before extending anything that looks like it already does what you were asked for. + +- A requirement is **prescriptive**: it states what should be true, never what happened. `status: retired` means the capability was BUILT and deliberately REMOVED — that entry is a prohibition, not history, and the right response to it is to stop, not to rebuild. +- The **node index** below answers *"does anything claim the thing I am about to change?"*. Match the literal FQN. +- **The ledger under it is not the same list.** A retired capability carries no `@implementedBy` — there is nothing left to point at — so it appears there and in no index. Read it before you conclude a capability does not exist yet. + +## Node index + +{{#hasNodeIndex}} +| Node | Kind | Claimed by | +|---|---|---| +{{#nodeIndex}} +| `{{{address}}}` | `{{{concern}}}` | {{{claims}}} | +{{/nodeIndex}} +{{#hasStatements}} + +### What those requirements say + +{{#statements}} +- `{{{path}}}` (`{{{subType}}}`) — {{{statement}}} +{{/statements}} +{{/hasStatements}} +{{/hasNodeIndex}} +{{^hasNodeIndex}} +No requirement resolves to a model node. The common reason is the ordinary one: an entry at L4 or L5 that simply declares no `@implementedBy` yet, which is legal and is what a `planned` entry looks like. The others are an entry sitting ABOVE the L4 link floor (where a claim is not permitted), a `retired` entry (where it is forbidden outright), and a claim that names a node nothing resolves — `meta verify` is what says which. +{{/hasNodeIndex}} + +## The ledger + +{{{ledger}}} diff --git a/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache b/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache new file mode 100644 index 0000000000..ad91a93c2f --- /dev/null +++ b/server/java/codegen-base/src/main/resources/metaobjects/templates/agent/schema.md.mustache @@ -0,0 +1,123 @@ +{{{generatedMarker}}} + +# Schema + +{{#physical}} +The physical shape of the `{{{dialect}}}` database this model generates. Read it before writing a query, a migration, or anything that names a table or a column. +{{/physical}} +{{^physical}} +The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. +{{/physical}} + +- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. +{{#hasMigrate}} +- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. +{{/hasMigrate}} +{{^hasMigrate}} +- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +{{/hasMigrate}} +- `Field` and `Declared` are the METADATA names. Edit those; the column name follows. + +{{#descriptionNudge}} +> **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text {{#hasMigrate}}`meta migrate`{{/hasMigrate}}{{^hasMigrate}}`meta schema`{{/hasMigrate}} emits as a `COMMENT ON`, so it lands in the database too. + +{{/descriptionNudge}} +{{#hasTables}} +## Tables + +{{#tables}} +### {{{heading}}} + +{{#tableDeclaredBy}} +Declared by `{{{.}}}`. +{{/tableDeclaredBy}} +{{#tableDescription}} + +> {{{.}}} +{{/tableDescription}} + +{{#physical}} +| Column | Field | Declared | SQL type | Null | Default | Key | +|---|---|---|---|---|---|---| +{{/physical}} +{{^physical}} +| Column | Field | Declared | Null | Key | +|---|---|---|---|---| +{{/physical}} +{{#columns}} +| `{{{name}}}` | {{{fieldCell}}} | {{{declaredCell}}} |{{#physical}} {{{sqlTypeCell}}} |{{/physical}} {{{nullCell}}} |{{#physical}} {{{defaultCell}}} |{{/physical}} {{{keyCell}}} | +{{/columns}} +{{#hasDescribed}} + +{{#described}} +- `{{{name}}}` — {{{text}}} +{{/described}} +{{/hasDescribed}} +{{#hasIndexes}} + +**Indexes** + +{{#indexes}} +- {{{.}}} +{{/indexes}} +{{/hasIndexes}} +{{#hasForeignKeys}} + +**Foreign keys** + +{{#foreignKeys}} +- {{{.}}} +{{/foreignKeys}} +{{/hasForeignKeys}} +{{#hasChecks}} + +**Checks** + +{{#checks}} +- {{{.}}} +{{/checks}} +{{/hasChecks}} + +{{/tables}} +{{/hasTables}} +{{#hasViews}} +## Views + +A view is generated from its projection's `origin.*` children{{#hasReportView}} or its report's dimensions and measures{{/hasReportView}} — it is derived, never hand-written. Editing the view SQL directly is drift the tool cannot see. + +{{#views}} +### {{{heading}}} + +{{#viewDeclaredBy}} +Declared by `{{{.}}}`. +{{/viewDeclaredBy}} +{{#hasLineage}} + +| Column | Lineage | +|---|---| +{{#lineage}} +| `{{{column}}}` | {{{text}}} | +{{/lineage}} +{{/hasLineage}} + +{{/views}} +{{/hasViews}} +{{#hasRelationships}} +## Relationships + +{{#relationships}} +- {{{.}}} +{{/relationships}} + +{{/hasRelationships}} +{{#hasEnums}} +## Enums + +Members are the values the wire and the generated types use.{{#physical}} Whether the DATABASE also refuses a value outside the set is that table's **Checks** above — an `@isArray` enum carries none, and neither does a view column.{{/physical}} + +| Field | Members | Storage | +|---|---|---| +{{#enums}} +| `{{{field}}}` | {{{members}}} | {{{storage}}} | +{{/enums}} +{{/hasEnums}} diff --git a/server/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.md.mustache b/server/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.md.mustache new file mode 100644 index 0000000000..a200094478 --- /dev/null +++ b/server/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.md.mustache @@ -0,0 +1,27 @@ +{{^embedded}} +# Requirements + +{{/embedded}} +{{{count}}} declared requirement{{{plural}}}, in declaration order. +{{#entries}} + +{{{heading}}} + +{{{facts}}} +{{#statement}} + +{{{.}}} +{{/statement}} +{{#counterexample}} + +{{{.}}} +{{/counterexample}} +{{#description}} + +{{{.}}} +{{/description}} +{{#implementedBy}} + +{{{.}}} +{{/implementedBy}} +{{/entries}} diff --git a/server/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.toon.mustache b/server/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.toon.mustache new file mode 100644 index 0000000000..cae64ef896 --- /dev/null +++ b/server/java/codegen-base/src/main/resources/metaobjects/templates/requirements/requirements.toon.mustache @@ -0,0 +1,2 @@ +requirements[{{{count}}}]{{{fields}}}:{{#rows}} + {{{line}}}{{/rows}} \ No newline at end of file diff --git a/server/python/src/metaobjects/agent_context/shipped/files/527e422aeec9a36d.md b/server/python/src/metaobjects/agent_context/shipped/files/527e422aeec9a36d.md new file mode 100644 index 0000000000..579a3509ae --- /dev/null +++ b/server/python/src/metaobjects/agent_context/shipped/files/527e422aeec9a36d.md @@ -0,0 +1,7 @@ +## Pages generated for this project + +`meta gen` writes these from the metadata (they are regenerated output, like the code). Read the +one for a tier before you change that tier: + +{{pageList}} + diff --git a/server/python/src/metaobjects/agent_context/shipped/manifest.json b/server/python/src/metaobjects/agent_context/shipped/manifest.json index dd3daf5969..bf05f04901 100644 --- a/server/python/src/metaobjects/agent_context/shipped/manifest.json +++ b/server/python/src/metaobjects/agent_context/shipped/manifest.json @@ -3,6 +3,7 @@ "docsRef": "main", "docsLinkPrefix": "https://github.com/metaobjectsdev/metaobjects/blob/", "skillsDir": ".claude/skills", + "agentPagesTemplate": "527e422aeec9a36d.md", "stacks": [ { "id": "typescript", diff --git a/server/rust/metaobjects-codegen/templates/agent/requirements.md.mustache b/server/rust/metaobjects-codegen/templates/agent/requirements.md.mustache new file mode 100644 index 0000000000..cb7cba06cb --- /dev/null +++ b/server/rust/metaobjects-codegen/templates/agent/requirements.md.mustache @@ -0,0 +1,34 @@ +{{{generatedMarker}}} + +# Requirements + +Read this before adding a capability, and before extending anything that looks like it already does what you were asked for. + +- A requirement is **prescriptive**: it states what should be true, never what happened. `status: retired` means the capability was BUILT and deliberately REMOVED — that entry is a prohibition, not history, and the right response to it is to stop, not to rebuild. +- The **node index** below answers *"does anything claim the thing I am about to change?"*. Match the literal FQN. +- **The ledger under it is not the same list.** A retired capability carries no `@implementedBy` — there is nothing left to point at — so it appears there and in no index. Read it before you conclude a capability does not exist yet. + +## Node index + +{{#hasNodeIndex}} +| Node | Kind | Claimed by | +|---|---|---| +{{#nodeIndex}} +| `{{{address}}}` | `{{{concern}}}` | {{{claims}}} | +{{/nodeIndex}} +{{#hasStatements}} + +### What those requirements say + +{{#statements}} +- `{{{path}}}` (`{{{subType}}}`) — {{{statement}}} +{{/statements}} +{{/hasStatements}} +{{/hasNodeIndex}} +{{^hasNodeIndex}} +No requirement resolves to a model node. The common reason is the ordinary one: an entry at L4 or L5 that simply declares no `@implementedBy` yet, which is legal and is what a `planned` entry looks like. The others are an entry sitting ABOVE the L4 link floor (where a claim is not permitted), a `retired` entry (where it is forbidden outright), and a claim that names a node nothing resolves — `meta verify` is what says which. +{{/hasNodeIndex}} + +## The ledger + +{{{ledger}}} diff --git a/server/rust/metaobjects-codegen/templates/agent/schema.md.mustache b/server/rust/metaobjects-codegen/templates/agent/schema.md.mustache new file mode 100644 index 0000000000..ad91a93c2f --- /dev/null +++ b/server/rust/metaobjects-codegen/templates/agent/schema.md.mustache @@ -0,0 +1,123 @@ +{{{generatedMarker}}} + +# Schema + +{{#physical}} +The physical shape of the `{{{dialect}}}` database this model generates. Read it before writing a query, a migration, or anything that names a table or a column. +{{/physical}} +{{^physical}} +The tables, columns and keys this model declares. Read it before writing a query, a migration, or anything that names a table or a column. SQL types, defaults, indexes, checks, constraint names and referential actions are not on this page: the migration files carry them. +{{/physical}} + +- The **DDL is not repeated here.** The migration files are the DDL, they are generated, and they are what runs — this page describes the schema they produce. +{{#hasMigrate}} +- Change the schema by changing the **metadata** and running `meta migrate`. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migrate. +{{/hasMigrate}} +{{^hasMigrate}} +- Change the schema by changing the **metadata** and writing the migration with the project's migration tool, from the schema `meta schema` prints. Never hand-apply SQL to a live database: it drifts from the migration history and collides at the next migration. +{{/hasMigrate}} +- `Field` and `Declared` are the METADATA names. Edit those; the column name follows. + +{{#descriptionNudge}} +> **Nothing in this model declares a `description`.** The tables and columns below are named but not explained. Adding `description` to an entity or a field is the single highest-value change to this page: it is what tells a reader *which* of two plausible columns to use, and it is the same text {{#hasMigrate}}`meta migrate`{{/hasMigrate}}{{^hasMigrate}}`meta schema`{{/hasMigrate}} emits as a `COMMENT ON`, so it lands in the database too. + +{{/descriptionNudge}} +{{#hasTables}} +## Tables + +{{#tables}} +### {{{heading}}} + +{{#tableDeclaredBy}} +Declared by `{{{.}}}`. +{{/tableDeclaredBy}} +{{#tableDescription}} + +> {{{.}}} +{{/tableDescription}} + +{{#physical}} +| Column | Field | Declared | SQL type | Null | Default | Key | +|---|---|---|---|---|---|---| +{{/physical}} +{{^physical}} +| Column | Field | Declared | Null | Key | +|---|---|---|---|---| +{{/physical}} +{{#columns}} +| `{{{name}}}` | {{{fieldCell}}} | {{{declaredCell}}} |{{#physical}} {{{sqlTypeCell}}} |{{/physical}} {{{nullCell}}} |{{#physical}} {{{defaultCell}}} |{{/physical}} {{{keyCell}}} | +{{/columns}} +{{#hasDescribed}} + +{{#described}} +- `{{{name}}}` — {{{text}}} +{{/described}} +{{/hasDescribed}} +{{#hasIndexes}} + +**Indexes** + +{{#indexes}} +- {{{.}}} +{{/indexes}} +{{/hasIndexes}} +{{#hasForeignKeys}} + +**Foreign keys** + +{{#foreignKeys}} +- {{{.}}} +{{/foreignKeys}} +{{/hasForeignKeys}} +{{#hasChecks}} + +**Checks** + +{{#checks}} +- {{{.}}} +{{/checks}} +{{/hasChecks}} + +{{/tables}} +{{/hasTables}} +{{#hasViews}} +## Views + +A view is generated from its projection's `origin.*` children{{#hasReportView}} or its report's dimensions and measures{{/hasReportView}} — it is derived, never hand-written. Editing the view SQL directly is drift the tool cannot see. + +{{#views}} +### {{{heading}}} + +{{#viewDeclaredBy}} +Declared by `{{{.}}}`. +{{/viewDeclaredBy}} +{{#hasLineage}} + +| Column | Lineage | +|---|---| +{{#lineage}} +| `{{{column}}}` | {{{text}}} | +{{/lineage}} +{{/hasLineage}} + +{{/views}} +{{/hasViews}} +{{#hasRelationships}} +## Relationships + +{{#relationships}} +- {{{.}}} +{{/relationships}} + +{{/hasRelationships}} +{{#hasEnums}} +## Enums + +Members are the values the wire and the generated types use.{{#physical}} Whether the DATABASE also refuses a value outside the set is that table's **Checks** above — an `@isArray` enum carries none, and neither does a view column.{{/physical}} + +| Field | Members | Storage | +|---|---|---| +{{#enums}} +| `{{{field}}}` | {{{members}}} | {{{storage}}} | +{{/enums}} +{{/hasEnums}} diff --git a/server/rust/metaobjects-codegen/templates/requirements/requirements.md.mustache b/server/rust/metaobjects-codegen/templates/requirements/requirements.md.mustache new file mode 100644 index 0000000000..a200094478 --- /dev/null +++ b/server/rust/metaobjects-codegen/templates/requirements/requirements.md.mustache @@ -0,0 +1,27 @@ +{{^embedded}} +# Requirements + +{{/embedded}} +{{{count}}} declared requirement{{{plural}}}, in declaration order. +{{#entries}} + +{{{heading}}} + +{{{facts}}} +{{#statement}} + +{{{.}}} +{{/statement}} +{{#counterexample}} + +{{{.}}} +{{/counterexample}} +{{#description}} + +{{{.}}} +{{/description}} +{{#implementedBy}} + +{{{.}}} +{{/implementedBy}} +{{/entries}} diff --git a/server/rust/metaobjects-codegen/templates/requirements/requirements.toon.mustache b/server/rust/metaobjects-codegen/templates/requirements/requirements.toon.mustache new file mode 100644 index 0000000000..cae64ef896 --- /dev/null +++ b/server/rust/metaobjects-codegen/templates/requirements/requirements.toon.mustache @@ -0,0 +1,2 @@ +requirements[{{{count}}}]{{{fields}}}:{{#rows}} + {{{line}}}{{/rows}} \ No newline at end of file diff --git a/server/typescript/packages/cli/src/commands/init.ts b/server/typescript/packages/cli/src/commands/init.ts index d9a235a221..a8ba852c08 100644 --- a/server/typescript/packages/cli/src/commands/init.ts +++ b/server/typescript/packages/cli/src/commands/init.ts @@ -5,6 +5,7 @@ import { INIT_DEFAULT_LIMIT, INIT_MAX_LIMIT, UNKNOWN_FIELDS_REJECT } from "@meta import { DEFAULT_CONFIG, ConfigSchema, saveConfig, PACKAGE_MANIFEST_FILE, DEFAULT_METADATA_DIR, DEFAULT_METAOBJECTS_DIR, DEPS_DIR, LOCK_FILE } from "@metaobjectsdev/sdk"; import { assemble, resolveAgentContextRoot, planScaffold, + ALWAYS_ON_PATH, AGENT_PAGES_TEMPLATE, renderAgentPagesSection, wiredAgentPages, withAgentPagesSection, AGENT_CONTEXT_MANIFEST_PATH, DEFAULT_SKILLS_DIR, normalizeSkillsDir, type Manifest, type Stack, } from "@metaobjectsdev/sdk/agent-context"; import { assertKnownStackValues, resolveStack } from "../lib/detect-stack.js"; @@ -423,7 +424,14 @@ async function writeAgentContext(opts: InitOptions, result: InitResult): Promise // An explicit --skills-dir wins; otherwise the directory this project chose last time, so a // refresh never quietly moves the skills back to the default. const skillsDir = normalizeSkillsDir(opts.skillsDir ?? prior?.skillsDir ?? DEFAULT_SKILLS_DIR); - let assembled = assemble({ contentRoot: resolveAgentContextRoot(), stack, docsRef: docsRefForVersion(cliVersion()), skillsDir }); + const contentRoot = resolveAgentContextRoot(); + let assembled = assemble({ contentRoot, stack, docsRef: docsRefForVersion(cliVersion()), skillsDir }); + // The always-on file points at the agent pages only when the project's last `gen` wrote one. + const pagesSection = renderAgentPagesSection( + readFileSyncWrap(join(contentRoot, "templates", AGENT_PAGES_TEMPLATE), "utf8"), + wiredAgentPages(opts.cwd), + ); + assembled = assembled.map((f) => (f.path === ALWAYS_ON_PATH ? { ...f, contents: withAgentPagesSection(f.contents, pagesSection) } : f)); if (opts.noSkills) assembled = assembled.filter((f) => !f.path.startsWith(`${skillsDir}/`)); const generatedBy = cliVersion(); diff --git a/server/typescript/packages/cli/test/docs-page-conformance.test.ts b/server/typescript/packages/cli/test/docs-page-conformance.test.ts index 1f22fa8aa1..5ce3191327 100644 --- a/server/typescript/packages/cli/test/docs-page-conformance.test.ts +++ b/server/typescript/packages/cli/test/docs-page-conformance.test.ts @@ -20,21 +20,24 @@ import { describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; -import { InMemoryStringSource, MetaDataLoader, physicalNamingOf } from "@metaobjectsdev/metadata"; +import { buildDocsView, InMemoryStringSource, MetaDataLoader, physicalNamingOf } from "@metaobjectsdev/metadata"; import type { MetaRoot } from "@metaobjectsdev/metadata"; import { resolveSchemaConventions } from "@metaobjectsdev/migrate-ts"; import { agentRequirementsPageData, agentSchemaPageData, + agentSchemaPageDataFromView, renderAgentRequirementsPage, renderAgentSchemaPage, - renderRequirementsMarkdown, renderRequirementsToon, requirementRows, + requirementRowsFromView, requirementsLedgerData, requirementsToonData, schemaInputFromRows, schemaRows, + schemaRowsFromView, + renderAgentSchemaPageFromView, } from "@metaobjectsdev/codegen-ts"; import { buildAgentSchemaInput } from "../src/lib/agent-schema.js"; @@ -55,11 +58,14 @@ async function outputsOf(root: MetaRoot, migrate: boolean): Promise(); const json = (v: unknown): string => `${JSON.stringify(v, null, 2)}\n`; - const rows = requirementRows(root); + // Every page starts from the docs view: the rows each port reads off its own view. + const view = buildDocsView({ root }); + const rows = requirementRowsFromView(view); + expect(requirementRows(root)).toEqual(rows); if (rows.length > 0) { - out.set("requirements.md", renderRequirementsMarkdown(rows)); out.set("requirements.toon", renderRequirementsToon(rows)); - out.set("data/requirements.md.json", json(requirementsLedgerData(rows))); + // The ledger agent/requirements.md embeds: the requirements template in its embedded form. + out.set("data/ledger.md.json", json(requirementsLedgerData(rows, { embedded: true }))); out.set("data/requirements.toon.json", json(requirementsToonData(rows))); // The rows layer (D0a): what both requirements pages, and the docs site, are built from. out.set("rows/requirements.json", json(rows)); @@ -82,15 +88,21 @@ async function outputsOf(root: MetaRoot, migrate: boolean): Promise 0 && { routes }), }); + // The storage section's physical facts come from the expected schema, which only a run with + // a dialect has; without one they stay null, as in every other port. + const schema = ctx.docs?.agentSchema?.(); + return schema === undefined ? view : withPhysicalStorage(view, schema); } diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts b/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts index 12a0c92921..4070e2ff54 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-requirements-page.ts @@ -8,22 +8,23 @@ // it, which for this repository's own ledger is 175 rows. // // So this page carries the same index PLUS a NODE index: every claimed node → the -// requirements claiming it, at every grain. It is an inversion of `walkRequirements`, not -// a second walk — the same resolution, read the other way, so the two indexes cannot -// disagree about what resolves. +// requirements claiming it, at every grain. It is the docs view's resolved `implementedBy` +// read the other way (`nodeIndexFromView`), so the two indexes cannot disagree about what +// resolves, and every port builds it from the same view. // // LITERAL FQNs ON EVERY LINE, deliberately and even where it is repetitive. An agent // retrieving over a long context finds a node by matching the token it is holding; a row // that says "the field above" is unreachable to it. This is also why the node index is // FLAT rather than nested under its owning object. // -// A CLAIM THAT DOES NOT RESOLVE IS OMITTED, silently, exactly as `walkRequirements` omits -// it. Resolution severity depends on `@status` and belongs to `meta verify`; a docs page +// A CLAIM THAT DOES NOT RESOLVE IS OMITTED, silently, exactly as the view marks it +// unresolved. Resolution severity depends on `@status` and belongs to `meta verify`; a docs page // that rendered a dangling reference as though it pointed somewhere would be asserting // the opposite of what the gate says. // // THE LEDGER IS EMBEDDED BELOW THE INDEX, and that duplication is deliberate rather than -// an oversight — the same content also lives at `requirements.md` when that surface is on. +// an oversight: this page is the one Markdown copy of the ledger (people read it in the +// explorer, the docs site). // The node index alone would omit exactly the entries the mechanism is MEASURED on: a // `retired` capability may carry no `@implementedBy` at all (FR-039 forbids it), so it // resolves to no node and appears in no node index. The one controlled finding behind this @@ -38,79 +39,18 @@ // `requirements` page's own template rendered in its embedded form, so the two cannot // disagree. -import { REQUIREMENT_ATTR_STATEMENT } from "@metaobjectsdev/metadata"; +import { buildDocsView } from "@metaobjectsdev/metadata"; import type { MetaData } from "@metaobjectsdev/metadata"; import type { Provider } from "@metaobjectsdev/render"; import { compareCodeUnits } from "../code-unit-order.js"; -import { GENERATED_HEADER } from "../constants.js"; -import { concernOf, walkRequirements } from "../requirement-walk.js"; import { frameworkTemplatesProvider } from "../render-engine/framework-provider.js"; import { renderDocPage } from "../render-engine/doc-page.js"; -import { requirementRows } from "./requirements-view.js"; +import { AGENT_PAGE_MARKER, nodeIndexFromView, requirementRowsFromView } from "./docs-view-pages.js"; import { renderRequirementsMarkdown } from "./requirements-markdown.js"; /** The shared template of `agent/requirements.md`. */ export const AGENT_REQUIREMENTS_PAGE_REF = "agent/requirements.md"; -const GENERATED_MARKER = ``; - -/** - * The address of any claimed node: the ROOT node's `resolutionKey()` (which carries the - * effective package), then the child-name path down to it. - * - * Built by walking parents rather than read off the node, because only a root-level node - * has a resolution key — a claimed FIELD has a bare name, and `Subscriber.status` and - * `Order.status` would collide in this index if the owner were dropped. - */ -function nodeAddress(node: MetaData): string { - const segments: string[] = []; - let cur: MetaData | undefined = node; - while (cur !== undefined) { - const parent: MetaData | undefined = cur.parent; - // The last node with a parent is the root-level one; the metadata ROOT itself has no - // name worth printing, so the walk stops when the next step would leave the model. - if (parent === undefined || parent.parent === undefined) { - segments.push(cur.resolutionKey()); - break; - } - segments.push(cur.name); - cur = parent; - } - return segments.reverse().join("."); -} - -interface NodeIndexEntry { - readonly address: string; - readonly concern: string; - readonly claims: { path: string; subType: string; level: number | undefined; status: string | undefined; statement: string | undefined }[]; -} - -/** Invert the walk: claimed node → the requirements that claim it. */ -export function buildNodeIndex( - root: MetaData, - inLedger?: (fqn: string) => boolean, -): NodeIndexEntry[] { - const byAddress = new Map(); - for (const walked of walkRequirements(root, inLedger)) { - const statement = walked.node.attr(REQUIREMENT_ATTR_STATEMENT); - for (const target of walked.targets) { - const address = nodeAddress(target.node); - let entry = byAddress.get(address); - if (entry === undefined) { - entry = { address, concern: concernOf(target.node), claims: [] }; - byAddress.set(address, entry); - } - entry.claims.push({ - path: walked.view.path, - subType: walked.view.subType, - level: walked.view.level, - status: walked.view.status, - statement: typeof statement === "string" && statement !== "" ? statement : undefined, - }); - } - } - return [...byAddress.values()].sort((a, b) => compareCodeUnits(a.address, b.address)); -} function mdCell(text: string): string { return text.replace(/\|/g, "\\|"); @@ -143,10 +83,11 @@ export function agentRequirementsPageData( inLedger?: (fqn: string) => boolean, provider?: Provider, ): AgentRequirementsPageData | undefined { - const rows = requirementRows(root, inLedger); + const view = buildDocsView({ root }); + const rows = requirementRowsFromView(view, inLedger); if (rows.length === 0) return undefined; - const index = buildNodeIndex(root, inLedger); + const index = nodeIndexFromView(view, inLedger); // The statements ride below the table: they are prose, they repeat across nodes a // shared architectural entry claims, and putting one in a cell forces the table wide. const stated = new Map(); @@ -159,7 +100,7 @@ export function agentRequirementsPageData( .sort((a, b) => compareCodeUnits(a[0], b[0])) .map(([path, { subType, statement }]) => ({ path, subType, statement: mdCell(oneLine(statement)) })); return { - generatedMarker: GENERATED_MARKER, + generatedMarker: AGENT_PAGE_MARKER, hasNodeIndex: index.length > 0, nodeIndex: index.map((entry) => ({ address: entry.address, diff --git a/server/typescript/packages/codegen-ts/src/generators/api-docs-file.ts b/server/typescript/packages/codegen-ts/src/generators/api-docs-file.ts index 50f3af220c..4051722f19 100644 --- a/server/typescript/packages/codegen-ts/src/generators/api-docs-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/api-docs-file.ts @@ -17,13 +17,12 @@ // this port's generators emit. Like every generator it runs when the project lists it, and // only then (ADR-0034 Amendment 9). // -// THE POINTER IS NO LONGER DEFERRED. This header used to record "surfacing the agent form -// (AGENT-API.md) to a coding agent via a pointer from the installed `.metaobjects/` -// context" as an agent-context-coordination follow-up. It was deferred, no roadmap item -// tracked it, and for as long as that held, the page existed and nothing routed an agent -// to it. `agent-context/templates/always-on.md.mustache` now names this file and the three -// `agent/` pages, and says when to read each. If you rename or move this artifact, that -// template is the other half. +// THE POINTER. The always-on file `meta init` writes (`.metaobjects/AGENTS.md`) names this file +// and the `agent/` pages, and says when to read each, but only once a `gen` has written them: +// `sdk/src/agent-context/agent-pages.ts` reads the committed `.gen-state/.hashes/` and inserts +// the section (`agent-context/templates/agent-pages.md.mustache`) above the rules, so a project +// that does not wire this generator is never sent to a file that is not there. If you rename +// this artifact, `AGENT_PAGES` there is the other half. import type { MetaObject } from "@metaobjectsdev/metadata"; import type { Generator, GeneratorFactory, EmittedFile } from "../generator.js"; diff --git a/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts b/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts new file mode 100644 index 0000000000..85b97dd8cf --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts @@ -0,0 +1,386 @@ +// The agent pages, built from the docs view (docs/features/docs-view.md). +// +// `requirements.toon`, `agent/requirements.md` and the model-only `agent/schema.md` are shared +// Mustache templates every port renders. The view is the one input every port builds the same +// bytes of, so the rows each page starts from are read off the view and nothing else: the +// requirement rows from `requirements`, the node index from each requirement's resolved +// `implementedBy`, and the schema from `storage` plus the members of the nodes it links. A +// port's builders are therefore ports of THIS file, over its own view; the cross-port corpus +// is fixtures/docs-page-conformance/. + +import type { + DocsView, + DocsViewAttr, + DocsViewMember, + DocsViewNode, + DocsViewTable, +} from "@metaobjectsdev/metadata"; +import { compareCodeUnits } from "../code-unit-order.js"; +import { GENERATED_HEADER } from "../constants.js"; +import type { Provider } from "@metaobjectsdev/render"; +import type { AgentSchemaInput } from "./agent-schema-input.js"; +import { requirementLedgerKey } from "../requirement-walk.js"; +import { frameworkTemplatesProvider } from "../render-engine/framework-provider.js"; +import { renderDocPage } from "../render-engine/doc-page.js"; +import type { RequirementRow } from "./requirements-view.js"; + +/** The marker on the first line of every agent page. */ +export const AGENT_PAGE_MARKER = ``; + +const opt = (s: string): string | undefined => (s === "" ? undefined : s); + +// ---- requirements ----------------------------------------------------------------------- + +/** + * The requirement rows of the view, in document order. `inLedger` is the collection's ledger + * predicate: a dependency's requirement the project did not inherit is left out. + */ +export function requirementRowsFromView(view: DocsView, inLedger?: (fqn: string) => boolean): RequirementRow[] { + return view.requirements + .filter((r) => inLedger === undefined || inLedger(requirementLedgerKey({ package: r.package, path: r.address }))) + .map((r) => ({ + path: r.address, + depth: r.depth, + title: opt(r.title), + subType: r.subType, + level: r.level ?? undefined, + status: opt(r.status), + disposition: opt(r.disposition), + trackedBy: r.trackedBy, + statement: opt(r.statement), + counterexample: opt(r.counterexample), + description: opt(r.description), + implementedBy: r.implementedBy.map((l) => l.ref), + claimedConcerns: [...new Set(r.implementedBy.filter((l) => l.resolves).map((l) => l.target.kind))], + })); +} + +export interface NodeIndexClaim { + readonly path: string; + readonly subType: string; + readonly level: number | undefined; + readonly status: string | undefined; + readonly statement: string | undefined; +} + +export interface NodeIndexEntry { + readonly address: string; + readonly concern: string; + readonly claims: NodeIndexClaim[]; +} + +/** Claimed node → the requirements that claim it, sorted by the node's id. A claim that does + * not resolve is left out, as `meta verify` is what reports it. */ +export function nodeIndexFromView(view: DocsView, inLedger?: (fqn: string) => boolean): NodeIndexEntry[] { + const byAddress = new Map(); + for (const r of view.requirements) { + if (inLedger !== undefined && !inLedger(requirementLedgerKey({ package: r.package, path: r.address }))) continue; + for (const link of r.implementedBy) { + if (!link.resolves) continue; + let entry = byAddress.get(link.target.id); + if (entry === undefined) { + entry = { address: link.target.id, concern: link.target.kind, claims: [] }; + byAddress.set(link.target.id, entry); + } + entry.claims.push({ + path: r.address, + subType: r.subType, + level: r.level ?? undefined, + status: opt(r.status), + statement: opt(r.statement), + }); + } + } + return [...byAddress.values()].sort((a, b) => compareCodeUnits(a.address, b.address)); +} + +// ---- schema ------------------------------------------------------------------------------- + +/** One table of the model-only rows layer (`expected/rows/schema.json`). */ +export interface SchemaRowsTable { + name: string; + schema?: string; + description?: string; + primaryKey: string[]; + columns: { name: string; nullable: boolean; identity?: string; description?: string }[]; + foreignKeys: { columns: string[]; refTable: string; refColumns: string[] }[]; +} + +export interface SchemaRowsLayer { + tables: SchemaRowsTable[]; + views: { name: string; schema?: string }[]; + declaredBy: Record; +} + +function storageKey(name: string, schema: string): string { + return schema === "" ? name : `${schema}.${name}`; +} + +/** The rows layer of the schema page, read off the view's storage: the shape + * `meta schema --as json` prints, less its physical facts. */ +export function schemaRowsFromView(view: DocsView): SchemaRowsLayer { + const declared: [string, string][] = []; + const tables = view.storage.tables.map((t) => { + declared.push([storageKey(t.name, t.schema), t.declaredBy.id]); + return { + name: t.name, + ...(t.schema !== "" && { schema: t.schema }), + ...(t.description !== "" && { description: t.description }), + primaryKey: t.primaryKey, + columns: t.columns.map((c) => ({ + name: c.name, + nullable: c.nullable, + ...(c.identity !== "" && { identity: c.identity }), + ...(c.description !== "" && { description: c.description }), + })), + foreignKeys: t.foreignKeys.map((f) => ({ columns: f.columns, refTable: f.refTable, refColumns: f.refColumns })), + }; + }); + const views = view.storage.views.map((v) => { + declared.push([storageKey(v.name, v.schema), v.declaredBy.id]); + return { name: v.name, ...(v.schema !== "" && { schema: v.schema }) }; + }); + declared.sort((a, b) => compareCodeUnits(a[0], b[0])); + return { tables, views, declaredBy: Object.fromEntries(declared) }; +} + +/** What `agent/schema.md.mustache` renders. `physical` is false: the model-only page. */ +export interface AgentSchemaViewPageData { + generatedMarker: string; + physical: false; + dialect: ""; + hasMigrate: boolean; + descriptionNudge: boolean; + hasTables: boolean; + tables: Record[]; + hasViews: boolean; + hasReportView: boolean; + views: Record[]; + hasRelationships: boolean; + relationships: string[]; + hasEnums: boolean; + enums: { field: string; members: string; storage: string }[]; +} + +const TYPE_OBJECT = "object"; +const TYPE_FIELD = "field"; +const TYPE_ORIGIN = "origin"; +const TYPE_RELATIONSHIP = "relationship"; +const KIND_REPORT = "object.report"; +const SUBTYPE_ENUM = "enum"; + +/** Every member of every node, by id. */ +function membersById(view: DocsView): Map { + const out = new Map(); + const visit = (m: DocsViewMember): void => { + out.set(m.id, m); + for (const g of m.memberGroups) g.members.forEach(visit); + }; + for (const n of view.nodes) for (const g of n.memberGroups) g.members.forEach(visit); + return out; +} + +function directMembers(n: DocsViewNode | DocsViewMember, type: string): DocsViewMember[] { + return n.memberGroups.find((g) => g.type === type)?.members ?? []; +} + +function attrValue(attrs: readonly DocsViewAttr[], name: string): unknown { + return attrs.find((a) => a.name === name)?.value; +} + +/** A string attribute as a page prints it: a resolved reference by its link's label (what the + * author wrote, relative to the model: `Owner.name`), anything else as its text. */ +function attrText(attrs: readonly DocsViewAttr[], name: string): string | undefined { + const a = attrs.find((x) => x.name === name); + if (a === undefined || typeof a.value !== "string") return undefined; + const first = a.values[0]; + const text = first?.link != null && !first.link.unresolved ? first.link.label : a.value; + return text === "" ? undefined : text; +} + +const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim(); +const cols = (names: readonly string[]): string => (names.length === 0 ? "—" : names.map((c) => `\`${c}\``).join(", ")); + +function keyCell(table: DocsViewTable, column: string): string { + const roles: string[] = []; + if (table.primaryKey.includes(column)) roles.push(table.primaryKey.length > 1 ? "PK (composite)" : "PK"); + const fk = table.foreignKeys.find((f) => f.columns.includes(column)); + if (fk !== undefined) roles.push(`FK → \`${fk.refTable}\``); + return roles.join(" · "); +} + +/** The lineage text of a view column, from its field's `origin.*` member. */ +function lineageOf(field: DocsViewMember | undefined): string | undefined { + const origin = field === undefined ? undefined : directMembers(field, TYPE_ORIGIN)[0]; + if (origin === undefined) return undefined; + const t = (name: string): string | undefined => attrText(origin.attrs, name); + switch (origin.subType) { + case "passthrough": + return `passthrough from \`${t("from") ?? "?"}\`` + (t("via") === undefined ? "" : ` via \`${t("via")}\``); + case "aggregate": + return `\`${t("agg") ?? "?"}\`` + (t("of") === undefined ? "" : ` of \`${t("of")}\``) + (t("via") === undefined ? "" : ` via \`${t("via")}\``); + case "first": + return "first" + (t("of") === undefined ? "" : ` \`${t("of")}\``) + (t("via") === undefined ? "" : ` via \`${t("via")}\``) + (t("orderBy") === undefined ? "" : ` ordered by \`${t("orderBy")}\``); + case "computed": + return "computed from a declared `@expr`"; + default: + return `\`origin.${origin.subType}\``; + } +} + +function cardinalityPhrase(cardinality: unknown, through: string | undefined): string { + if (cardinality === "many") return through !== undefined ? "many-to-many" : "one-to-many"; + if (cardinality === "one") return "many-to-one"; + return "cardinality not declared"; +} + +/** + * The data `agent/schema.md.mustache` renders for the model-only page, built from the view + * alone. `hasMigrate`: the project chose a `meta migrate` dialect (`migrate.dialect` in + * `.metaobjects/config.json`). Undefined when the model declares no table and no view: no page. + */ +export function agentSchemaPageDataFromView(view: DocsView, hasMigrate: boolean): AgentSchemaViewPageData | undefined { + const { tables, views } = view.storage; + if (tables.length === 0 && views.length === 0) return undefined; + const members = membersById(view); + const byOrder = [...view.nodes].sort((a, b) => a.order - b.order); + + const tableData = tables.map((t) => { + const k = storageKey(t.name, t.schema); + const described = t.columns.filter((c) => c.description !== ""); + const fks = t.foreignKeys.map((f) => `${cols(f.columns)} → \`${f.refTable}\`(${cols(f.refColumns)})`); + const fieldName = (id: string): string => members.get(id)?.name ?? ""; + return { + heading: `\`${k}\``, + tableDeclaredBy: t.declaredBy.id, + ...(t.description !== "" && { tableDescription: oneLine(t.description) }), + columns: t.columns.map((c) => ({ + name: c.name, + fieldCell: c.field === null ? "" : `\`${fieldName(c.field.id)}\``, + declaredCell: c.field === null ? "" : `\`${c.field.kind}\``, + sqlTypeCell: "", + nullCell: c.nullable ? "yes" : "no", + defaultCell: "", + keyCell: keyCell(t, c.name), + })), + hasDescribed: described.length > 0, + described: described.map((c) => ({ name: c.name, text: oneLine(c.description) })), + hasIndexes: false, + indexes: [], + hasForeignKeys: fks.length > 0, + foreignKeys: fks, + hasChecks: false, + checks: [], + }; + }); + + const viewData = views.map((v) => { + const lineage = v.columns.flatMap((c) => { + const text = lineageOf(c.field === null ? undefined : members.get(c.field.id)); + return text === undefined ? [] : [{ column: c.name, text }]; + }); + return { + heading: `\`${storageKey(v.name, v.schema)}\``, + viewDeclaredBy: v.declaredBy.id, + hasLineage: lineage.length > 0, + lineage, + }; + }); + + // Every relationship as written, in declaration order of its object. + const relationships: string[] = []; + for (const n of byOrder) { + if (n.type !== TYPE_OBJECT) continue; + for (const rel of directMembers(n, TYPE_RELATIONSHIP)) { + const through = attrText(rel.attrs, "through"); + const onDelete = attrText(rel.attrs, "onDelete"); + const parts = [`\`${n.id}.${rel.name}\``, `\`${rel.subType}\``]; + parts.push(`${cardinalityPhrase(attrValue(rel.attrs, "cardinality"), through)} → \`${attrText(rel.attrs, "objectRef") ?? "?"}\``); + if (through !== undefined) parts.push(`through \`${through}\``); + if (onDelete !== undefined) parts.push(`on delete \`${onDelete}\``); + relationships.push(parts.join(" · ")); + } + } + + // Every enum field of a table-backed object, in declaration order of its object. + const tableBacked = new Set(tables.flatMap((t) => t.objects.map((o) => o.id))); + const enums: AgentSchemaViewPageData["enums"] = []; + for (const n of byOrder) { + if (!tableBacked.has(n.id)) continue; + for (const f of directMembers(n, TYPE_FIELD)) { + if (f.subType !== SUBTYPE_ENUM) continue; + const values = attrValue(f.attrs, "values"); + const list = Array.isArray(values) ? values.map(String) : []; + if (list.length === 0) continue; + const intMap = attrValue(f.attrs, "intValueMap"); + const storage = + typeof intMap === "object" && intMap !== null && !Array.isArray(intMap) + ? `int-backed (${list.map((m) => `${m}=${String((intMap as Record)[m])}`).join(", ")})` + : "string-backed"; + enums.push({ field: `${n.id}.${f.name}`, members: list.map((m) => `\`${m}\``).join(", "), storage }); + } + } + + const anyDescription = tables.some((t) => t.description !== "" || t.columns.some((c) => c.description !== "")); + return { + generatedMarker: AGENT_PAGE_MARKER, + physical: false, + dialect: "", + hasMigrate, + descriptionNudge: !anyDescription && tables.length > 0, + hasTables: tableData.length > 0, + tables: tableData, + hasViews: viewData.length > 0, + hasReportView: views.some((v) => v.objects.some((o) => o.kind === KIND_REPORT)), + views: viewData, + hasRelationships: relationships.length > 0, + relationships, + hasEnums: enums.length > 0, + enums, + }; +} + +/** The model-only `agent/schema.md`, rendered from the view; "" when the model declares no + * table and no view. The page ends with exactly one line break. */ +export function renderAgentSchemaPageFromView(view: DocsView, hasMigrate: boolean, provider?: Provider): string { + const data = agentSchemaPageDataFromView(view, hasMigrate); + if (data === undefined) return ""; + const page = renderDocPage("agent/schema.md", data, provider ?? frameworkTemplatesProvider, "agent/schema.md"); + return `${page.replace(/\n+$/, "")}\n`; +} + +/** + * The view with its storage section's physical facts filled from the expected schema `meta + * migrate` diffs against (SQL types, defaults, indexes, checks, constraint names, referential + * actions). Only the TypeScript toolchain has that schema; a table it does not describe keeps + * its nulls. The view is returned, changed in place. + */ +export function withPhysicalStorage(view: DocsView, schema: AgentSchemaInput): DocsView { + const storage = view.storage; + storage.physical = true; + storage.dialect = schema.dialect; + for (const table of storage.tables) { + const match = + schema.tables.find((t) => t.name === table.name && (t.schema ?? "") === table.schema) ?? + (table.schema === "" ? schema.tables.find((t) => t.name === table.name) : undefined); + if (match === undefined) continue; + for (const column of table.columns) { + const c = match.columns.find((x) => x.name === column.name); + if (c === undefined) continue; + column.sqlType = schema.columnType(c); + column.default = c.default?.value ?? null; + } + for (const fk of table.foreignKeys) { + const f = match.foreignKeys.find( + (x) => x.refTable === fk.refTable && x.columns.join("\0") === fk.columns.join("\0"), + ); + if (f === undefined) continue; + fk.name = f.name; + fk.onDelete = f.onDelete ?? null; + fk.onUpdate = f.onUpdate ?? null; + } + table.indexes = match.indexes.map((i) => ({ name: i.name, columns: [...i.columns], unique: i.unique })); + table.checks = match.checks.map((c) => ({ name: c.name, expression: c.expression })); + } + return view; +} diff --git a/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts b/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts index 6843d0366d..7d24a246bb 100644 --- a/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/requirements-file.ts @@ -13,9 +13,9 @@ // AN EMPTY LEDGER EMITS ZERO FILES, not an empty page, so a project without a ledger that // lists this generator gets nothing rather than a page saying there is nothing. // -// BOTH FILES, UNCONDITIONALLY — deliberately not behind an option: a drift gate wants the -// machine-readable artifact committed regardless of who ran it or from what kind of -// terminal. +// ONE FILE, the machine-readable `requirements.toon` with its declared row count. The +// human page `requirements.md` is retired: people read the ledger in the explorer (the +// `docs-site` generator), and agents read it embedded in `agent/requirements.md`. import { type EmittedFile, @@ -23,14 +23,11 @@ import { type GeneratorFactory, oncePerRun, } from "../generator.js"; -import { renderRequirementsMarkdown } from "./requirements-markdown.js"; import { renderRequirementsToon } from "./requirements-toon.js"; import { requirementRows } from "./requirements-view.js"; import { DOCS_TARGET_NAME } from "../docs-run.js"; import { docsTemplateRoot, projectProvider } from "../render-engine/framework-provider.js"; -/** The human-facing index. */ -const MARKDOWN_FILENAME = "requirements.md"; /** The machine-facing artifact — see requirements-toon.ts for why TOON. */ const TOON_FILENAME = "requirements.toon"; @@ -39,8 +36,8 @@ export interface RequirementsFileOpts { outDir?: string; /** Named output target. Default `"docs"`, which `targets` must declare. */ target?: string; - /** Directory whose `templates/requirements/requirements.{md,toon}.mustache` override the - * shipped pages, relative to the project. Default: the project's own `templates/`. */ + /** Directory whose `templates/requirements/requirements.toon.mustache` overrides the + * shipped page, relative to the project. Default: the project's own `templates/`. */ templates?: string; } @@ -61,7 +58,6 @@ export const requirementsFile = function requirementsFile( const provider = projectProvider(docsTemplateRoot(ctx, opts?.templates)); const files: EmittedFile[] = [ - { path: `${dirPrefix}${MARKDOWN_FILENAME}`, content: renderRequirementsMarkdown(rows, { provider }) }, { path: `${dirPrefix}${TOON_FILENAME}`, content: renderRequirementsToon(rows, provider) }, ]; return files; diff --git a/server/typescript/packages/codegen-ts/src/generators/requirements-view.ts b/server/typescript/packages/codegen-ts/src/generators/requirements-view.ts index 0929a206cf..312da1033e 100644 --- a/server/typescript/packages/codegen-ts/src/generators/requirements-view.ts +++ b/server/typescript/packages/codegen-ts/src/generators/requirements-view.ts @@ -4,12 +4,10 @@ // // Design: docs/superpowers/specs/2026-08-21-requirements-doc-surface-design.md // -// PROJECTS OVER `walkRequirements()`, NEVER RE-WALKS. That walk already resolves the -// depth-first traversal, the dotted `path` (hierarchy IS nesting), and the -// `@implementedBy` targets, and it is what `requirementTests()` is built on. Sharing it -// means the doc view and the generated stubs agree about what the ledger contains by -// construction; two walks kept in step by hand is exactly the drift this surface exists -// to remove. +// READ OFF THE DOCS VIEW, NEVER RE-WALKED. The view's `requirements` already hold the +// depth-first order, the dotted address (hierarchy IS nesting) and each `@implementedBy` +// as written and as resolved, through the resolver the requirement gate uses; every port +// builds the same view, so every port's pages start from the same rows. // // `notes` IS DELIBERATELY ABSENT FROM THIS TYPE, not merely unread. `documentation.json` // charters it internal-only, never emitted to a user-facing doc surface, and the @@ -17,19 +15,12 @@ // cannot leak a field the projection never carries — which is a stronger guarantee than // asking every renderer to remember. // -// RESOLVING ACCESSORS ONLY (ADR-0039). Every read below goes through MetaRequirement's -// resolving accessors or the resolving `attr()`, so a requirement that `extends` an -// abstract parent inherits its `@level` / `@status` / statement rather than projecting -// them as undefined. No `own*()` call belongs in this file. +// The view reads effective attributes (ADR-0039), so a requirement that `extends` an +// abstract parent carries its inherited `@level` / `@status` / statement. -import { - DOC_ATTR_DESCRIPTION, - DOC_ATTR_TITLE, - REQUIREMENT_ATTR_STATEMENT, - REQUIREMENT_ATTR_COUNTEREXAMPLE, -} from "@metaobjectsdev/metadata"; +import { buildDocsView } from "@metaobjectsdev/metadata"; import type { MetaData } from "@metaobjectsdev/metadata"; -import { walkRequirements } from "../requirement-walk.js"; +import { requirementRowsFromView } from "./docs-view-pages.js"; /** One requirement, projected for rendering. Ordered depth-first, declaration order. */ export interface RequirementRow { @@ -62,20 +53,11 @@ export interface RequirementRow { readonly claimedConcerns: readonly string[]; } -/** Reads a resolving string attr, normalising "declared but empty" to undefined so a - * renderer has one absent-case to handle rather than two. */ -function stringAttr(node: MetaData, name: string): string | undefined { - // `attr()` is the RESOLVING accessor in TypeScript (ADR-0039). Note the cross-port - // naming inversion this repo records: Python's `attr()` is own-only, TS's resolves. - const raw = node.attr(name); - if (typeof raw !== "string") return undefined; - return raw.length > 0 ? raw : undefined; -} - /** * Project every `requirement.*` node in the project's ledger — nested ones included — into - * render-ready rows. `inLedger` is the collection's ledger predicate, as `walkRequirements` - * reads it: a dependency's requirement the project did not inherit is not listed. + * render-ready rows, read off the docs view (`requirementRowsFromView`), which every port + * builds alike. `inLedger` is the collection's ledger predicate: a dependency's requirement + * the project did not inherit is not listed. * * Returns `[]` for a model declaring no requirements, which is what lets the surface * emit NOTHING rather than an empty page, and is in turn what makes turning the surface @@ -85,24 +67,5 @@ export function requirementRows( root: MetaData, inLedger?: (fqn: string) => boolean, ): RequirementRow[] { - return walkRequirements(root, inLedger).map((walked) => { - const { node, view, targets } = walked; - return { - path: view.path, - // Derived rather than threaded: a separately-tracked depth could drift from the - // path that renders beside it, and there is only one right answer. - depth: view.path.split(".").length - 1, - title: stringAttr(node, DOC_ATTR_TITLE), - subType: view.subType, - level: view.level, - status: view.status, - disposition: node.disposition(), - trackedBy: node.trackedBy(), - statement: stringAttr(node, REQUIREMENT_ATTR_STATEMENT), - counterexample: stringAttr(node, REQUIREMENT_ATTR_COUNTEREXAMPLE), - description: stringAttr(node, DOC_ATTR_DESCRIPTION), - implementedBy: node.implementedBy(), - claimedConcerns: [...new Set(targets.map((t) => t.concern))], - }; - }); + return requirementRowsFromView(buildDocsView({ root }), inLedger); } diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index 12d10972d2..be199360a7 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -461,6 +461,21 @@ export { type AgentSchemaPageData, type AgentSchemaPageOptions, } from "./generators/agent-schema-page.js"; +// The agent pages' rows, read off the docs view: what every port's builders are ports of. +export { + AGENT_PAGE_MARKER, + agentSchemaPageDataFromView, + renderAgentSchemaPageFromView, + withPhysicalStorage, + nodeIndexFromView, + requirementRowsFromView, + schemaRowsFromView, + type AgentSchemaViewPageData, + type NodeIndexClaim, + type NodeIndexEntry, + type SchemaRowsLayer, + type SchemaRowsTable, +} from "./generators/docs-view-pages.js"; // The rows layer beneath the model-only schema page (1.3.0 D0a): a subset of the // `meta schema --as json` shape, pinned by the docs-page corpus and shared with the docs site. export { diff --git a/server/typescript/packages/codegen-ts/src/reference/requirements.ts b/server/typescript/packages/codegen-ts/src/reference/requirements.ts index a3e80ce948..2e8a3d436e 100644 --- a/server/typescript/packages/codegen-ts/src/reference/requirements.ts +++ b/server/typescript/packages/codegen-ts/src/reference/requirements.ts @@ -6,19 +6,18 @@ // shebang is `#!/usr/bin/env node` — so it runs under NODE even in a Bun project. Do not // reach for `Bun.*` globals here; they are undefined and take the whole run down with // `Bun is not defined`. Use `node:` builtins instead. -// targets: Markdown for people and TOON for tools. Neither imports anything. +// targets: TOON for tools. It imports nothing. // use-when: you want to change how the requirement ledger is written as documentation: // which files, where they land, or what they hold. The packaged // `requirementsFile()` writes them without this file; eject it only to // change them. -// emits: into the `docs` target: requirements.md, the human index, and -// requirements.toon, the machine-readable form a drift gate can commit. A -// project that declares no `requirement.*` node gets neither file. -// customize: the file names, the output directory (`outDir`), and whether both forms are -// written (`generate`). The two renderers and the projection they read -// (`requirements-markdown`, `requirements-toon`, `requirements-view`) are -// copied beside it into codegen/templates/. -// composes-with: agent-docs (its `requirements.md` page is built from the same projection). +// emits: into the `docs` target: requirements.toon, the machine-readable ledger a +// drift gate can commit. People read the ledger in the explorer (`docs-site`). +// A project that declares no `requirement.*` node gets no file. +// customize: the file name, the output directory (`outDir`) and what is written +// (`generate`). The renderer and the rows it reads (`requirements-toon`, +// `requirements-view`, `docs-view-pages`) are copied beside it. +// composes-with: agent-docs (its `agent/requirements.md` page is built from the same rows). // // HOW IT RUNS. Like every generator: list it in `generators` in metaobjects.config.ts, with // a `docs` target declared, and `meta gen` writes the files (`meta verify --codegen` checks @@ -30,8 +29,8 @@ // // METADATA ALONE: this generator reads `ctx.loadedRoot` and NOTHING else (a page template // under the project's `templates/requirements/` shapes the layout and adds no fact). An EMPTY LEDGER -// EMITS ZERO FILES, not an empty page. BOTH FILES, UNCONDITIONALLY: a drift gate wants the -// machine-readable artifact committed regardless of who ran it. +// EMITS ZERO FILES, not an empty page. The file is written unconditionally: a drift gate wants +// the machine-readable artifact committed regardless of who ran it. import { docsTemplateRoot, @@ -42,12 +41,9 @@ import { type GeneratorFactory, DOCS_TARGET_NAME, } from "@metaobjectsdev/codegen-ts/engine"; -import { renderRequirementsMarkdown } from "../generators/requirements-markdown.js"; import { renderRequirementsToon } from "../generators/requirements-toon.js"; import { requirementRows } from "../generators/requirements-view.js"; -/** The human-facing index. */ -const MARKDOWN_FILENAME = "requirements.md"; /** The machine-facing artifact — see requirements-toon.ts for why TOON. */ const TOON_FILENAME = "requirements.toon"; @@ -56,8 +52,8 @@ export interface RequirementsFileOpts { outDir?: string; /** Named output target. Default `"docs"`, which `targets` must declare. */ target?: string; - /** Directory whose `templates/requirements/requirements.{md,toon}.mustache` override the - * shipped pages, relative to the project. Default: the project's own `templates/`. */ + /** Directory whose `templates/requirements/requirements.toon.mustache` overrides the + * shipped page, relative to the project. Default: the project's own `templates/`. */ templates?: string; } @@ -78,7 +74,6 @@ export const requirementsFile = function requirementsFile( const provider = projectProvider(docsTemplateRoot(ctx, opts?.templates)); const files: EmittedFile[] = [ - { path: `${dirPrefix}${MARKDOWN_FILENAME}`, content: renderRequirementsMarkdown(rows, { provider }) }, { path: `${dirPrefix}${TOON_FILENAME}`, content: renderRequirementsToon(rows, provider) }, ]; return files; diff --git a/server/typescript/packages/metadata/src/docs-view/build.ts b/server/typescript/packages/metadata/src/docs-view/build.ts index 5749839b53..279101b16d 100644 --- a/server/typescript/packages/metadata/src/docs-view/build.ts +++ b/server/typescript/packages/metadata/src/docs-view/build.ts @@ -56,6 +56,7 @@ import { type DocsViewSlice, type DocsViewStatusCount, } from "./types.js"; +import { buildStorage } from "./storage.js"; export interface DocsViewInput { /** The loaded, resolved model. */ @@ -660,6 +661,14 @@ export function buildDocsView(input: DocsViewInput): DocsView { requirements, advisories, slices: slicesOf(b, nodes, requirements), + storage: buildStorage(b.root, { + node: (md) => b.linkTo(md, md.name), + member: (owner, field) => { + const top = b.canonical.get(owner); + const row = top?.children.find((c) => c.md === field); + return row === undefined ? null : b.link(row); + }, + }), }; } diff --git a/server/typescript/packages/metadata/src/docs-view/storage.ts b/server/typescript/packages/metadata/src/docs-view/storage.ts new file mode 100644 index 0000000000..fcdfdcc781 --- /dev/null +++ b/server/typescript/packages/metadata/src/docs-view/storage.ts @@ -0,0 +1,334 @@ +// The docs view's `storage` section: the tables and views the model declares, named by the +// port's own naming helpers (docs/features/docs-view.md, "storage"). +// +// MODEL-ONLY, like the schema page a port without the expected schema writes (design call 17 +// of fixtures/docs-page-conformance/): a table per concrete object whose primary source is a +// writable, managed table (abstract bases and sourceless values have none; a TPH subtype +// shares its base's table and adds its own columns after the base's, nullable), a view per +// object whose primary source is a view. The physical facts (SQL type, default, indexes, +// checks, constraint names, referential actions) are `null` here; the TypeScript run fills +// them from the expected schema when it has one (codegen-ts `withPhysicalStorage`). + +import type { MetaData } from "../shared/meta-data.js"; +import type { MetaObject } from "../core/object/meta-object.js"; +import type { MetaField } from "../core/field/meta-field.js"; +import type { MetaSource } from "../persistence/source/meta-source.js"; +import { isMetaObject, isMetaSource } from "../shared/node-guards.js"; +import { TYPE_IDENTITY, TYPE_ORIGIN, TYPE_VALIDATOR } from "../shared/base-types.js"; +import { DOC_ATTR_DESCRIPTION } from "../core/documentation/doc-constants.js"; +import { OBJECT_ATTR_DISCRIMINATOR, OBJECT_ATTR_DISCRIMINATOR_VALUE } from "../core/object/object-constants.js"; +import { + FIELD_ATTR_OBJECT_REF, + FIELD_ATTR_REQUIRED, + FIELD_ATTR_STORAGE, + FIELD_SUBTYPE_OBJECT, + STORAGE_FLATTENED, +} from "../core/field/field-constants.js"; +import { + GENERATION_INCREMENT, + GENERATION_UUID, + IDENTITY_ATTR_FIELDS, + IDENTITY_ATTR_GENERATION, + IDENTITY_REFERENCE_ATTR_ENFORCE, + IDENTITY_REFERENCE_ATTR_REFERENCES, + IDENTITY_SUBTYPE_REFERENCE, +} from "../core/identity/identity-constants.js"; +import { VALIDATOR_SUBTYPE_REQUIRED } from "../core/validator/validator-constants.js"; +import { SOURCE_ATTR_SCHEMA, SOURCE_KIND_VIEW } from "../persistence/source/source-constants.js"; +import { + applyColumnNamingStrategy, + physicalNamingOf, + primaryRdbSource, + resolveColumnName, + resolveFlattenedColumnName, +} from "../naming.js"; +import { refTarget, splitChildTail } from "../naming-refs.js"; +import type { + DocsViewColumn, + DocsViewForeignKey, + DocsViewLink, + DocsViewStorage, + DocsViewStoredView, + DocsViewTable, + DocsViewViewColumn, +} from "./types.js"; + +/** Links into the view, from the builder that owns the walk. */ +export interface StorageLinks { + /** The top-level node's link. */ + node(md: MetaData): DocsViewLink; + /** The link to `field` as a member of the top-level `owner` (its own row of an inherited one). */ + member(owner: MetaData, field: MetaData): DocsViewLink | null; +} + +const byCodeUnit = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0); + +function description(node: MetaData): string { + const v = node.attr(DOC_ATTR_DESCRIPTION); + return typeof v === "string" ? v : ""; +} + +function schemaOf(source: MetaSource): string { + const v = source.attr(SOURCE_ATTR_SCHEMA); + return typeof v === "string" ? v : ""; +} + +function isRequired(field: MetaData): boolean { + // ADR-0039: resolving — @required and validator.required may be inherited via extends. + if (field.attr(FIELD_ATTR_REQUIRED) === true) return true; + return field.children().some((c) => c.type === TYPE_VALIDATOR && c.subType === VALIDATOR_SUBTYPE_REQUIRED); +} + +function isDerived(field: MetaData): boolean { + // ADR-0039 own (category 4): origin.* never inherits (ADR-0029). + return field.ownChildren().some((c) => c.type === TYPE_ORIGIN); +} + +/** The `@discriminator`-bearing ANCESTOR of `entity`, or undefined. */ +function discriminatorBase(entity: MetaData): MetaData | undefined { + for (let a = entity.superData; a !== undefined; a = a.superData) { + // ADR-0039 sanctioned own: an explicit super-resolution walk reads each ancestor's own attr. + if (a.ownAttr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) return a; + } + return undefined; +} + +function isTphSubtype(entity: MetaData): boolean { + return entity.attr(OBJECT_ATTR_DISCRIMINATOR_VALUE) !== undefined && discriminatorBase(entity) !== undefined; +} + +function tphConcreteSubtypes(base: MetaObject, objects: readonly MetaObject[]): MetaObject[] { + if (base.attr(OBJECT_ATTR_DISCRIMINATOR) === undefined) return []; + return objects.filter( + (o) => !o.isAbstract && o.attr(OBJECT_ATTR_DISCRIMINATOR_VALUE) !== undefined && discriminatorBase(o) === base, + ); +} + +function identityFields(identity: MetaData): string[] { + const v = identity.attr(IDENTITY_ATTR_FIELDS); + if (typeof v === "string") return v.split(",").map((s) => s.trim()).filter((s) => s !== ""); + return Array.isArray(v) ? v.map(String) : []; +} + +function columnOf(obj: MetaObject, name: string): string { + const f = obj.findField(name); + return f !== undefined ? resolveColumnName(f) : applyColumnNamingStrategy(name, physicalNamingOf(obj).columns); +} + +function isFlattened(field: MetaField): boolean { + return field.subType === FIELD_SUBTYPE_OBJECT && field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED; +} + +interface RawColumn { + name: string; + nullable: boolean; + identity: string; + description: string; +} + +function rawColumn(field: MetaData, isPk: boolean, generation: string, name: string): RawColumn { + return { + name, + nullable: !isPk && !isRequired(field), + identity: isPk && (generation === GENERATION_INCREMENT || generation === GENERATION_UUID) ? generation : "", + description: description(field), + }; +} + +function fieldColumns(field: MetaField, isPk: boolean, generation: string): RawColumn[] { + if (isFlattened(field)) { + const target = refTarget(field, FIELD_ATTR_OBJECT_REF); + if (!isMetaObject(target)) return []; + return target.fields().map((nested) => rawColumn(nested, false, "", resolveFlattenedColumnName(field, nested))); + } + return [rawColumn(field, isPk, generation, resolveColumnName(field))]; +} + +/** The referenced key's columns: an explicit dotted tail on `@references`, else the target's + * primary identity (its first field), else `id`. */ +function targetColumns(ref: MetaData, target: MetaObject): string[] { + const raw = ref.attr(IDENTITY_REFERENCE_ATTR_REFERENCES); + const tail = typeof raw === "string" ? splitChildTail(raw).tail : ""; + const explicit = tail.replace(/^\./, "").split(",").map((s) => s.trim()).filter((s) => s !== ""); + let names = explicit; + if (names.length === 0) { + const identity = target.primaryIdentity(); + const pk = identity !== undefined ? identityFields(identity) : []; + names = [pk[0] ?? "id"]; + } + return names.map((n) => columnOf(target, n)); +} + +function foreignKeys(entity: MetaObject, objects: readonly MetaObject[], tableOf: Map): DocsViewForeignKey[] { + const isRef = (c: MetaData): boolean => c.type === TYPE_IDENTITY && c.subType === IDENTITY_SUBTYPE_REFERENCE; + const refs: [MetaObject, MetaData][] = entity.children().filter(isRef).map((c) => [entity, c]); + if (entity.attr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) { + const baseNames = new Set(refs.map(([, r]) => r.name)); + for (const sub of tphConcreteSubtypes(entity, objects)) { + for (const c of sub.children()) if (isRef(c) && !baseNames.has(c.name)) refs.push([sub, c]); + } + } + const fks: DocsViewForeignKey[] = []; + for (const [holder, ref] of refs) { + if (ref.attr(IDENTITY_REFERENCE_ATTR_ENFORCE) === false) continue; // a logical-only reference is no constraint + const target = refTarget(ref, IDENTITY_REFERENCE_ATTR_REFERENCES); + if (!isMetaObject(target)) continue; + const refTable = tableOf.get(target); + if (refTable === undefined || refTable === "") continue; + const names = identityFields(ref); + if (names.length === 0) continue; + const fk: DocsViewForeignKey = { + columns: names.map((n) => columnOf(holder, n)), + refTable, + refColumns: targetColumns(ref, target), + name: null, + onDelete: null, + onUpdate: null, + }; + // Two subtypes may declare the same column: one constraint. + const same = (a: DocsViewForeignKey): boolean => + a.refTable === fk.refTable && a.columns.join("\0") === fk.columns.join("\0") && a.refColumns.join("\0") === fk.refColumns.join("\0"); + if (!fks.some(same)) fks.push(fk); + } + return fks; +} + +function key(name: string, schema: string): string { + return schema === "" ? name : `${schema}.${name}`; +} + +/** The storage section of the docs view for the top-level nodes of `root`, in declaration order. */ +export function buildStorage(root: MetaData, links: StorageLinks): DocsViewStorage { + const objects = root.children().filter(isMetaObject); + + // Pass 1: which objects own a table, and which are only a foreign-key target. + const entities: [MetaObject, MetaSource][] = []; + const targetOnly: [MetaObject, MetaSource][] = []; + const tphMembers: [MetaObject, MetaData][] = []; + for (const obj of objects) { + const base = discriminatorBase(obj); + if (base !== undefined && (obj.isAbstract || isTphSubtype(obj))) { + tphMembers.push([obj, base]); + continue; + } + if (obj.isAbstract) continue; + if (!obj.children().some((c) => isMetaSource(c) && c.isWritable())) continue; + const source = primaryRdbSource(obj); + if (source === undefined) continue; + // ADR-0039 sanctioned own: @unmanaged is read off the object's OWN writable source. + const own = obj.ownChildren().find((c): c is MetaSource => isMetaSource(c) && c.isWritable()); + if (own !== undefined && own.isUnmanaged) { + targetOnly.push([obj, source]); + continue; + } + entities.push([obj, source]); + } + const tableOf = new Map([...entities, ...targetOnly].map(([o, s]) => [o, s.physicalName] as const)); + for (const [member, base] of tphMembers) { + const name = tableOf.get(base); + if (name !== undefined && !tableOf.has(member)) tableOf.set(member, name); + } + + // Every object at each storage key, in declaration order: the column → declaring field map + // (first writer wins on a shared table) and the objects a page lists. + const atKey = new Map(); + for (const obj of objects) { + const source = primaryRdbSource(obj); + if (source === undefined) continue; + const k = key(source.physicalName, schemaOf(source)); + atKey.set(k, [...(atKey.get(k) ?? []), obj]); + } + const fieldOf = (k: string): Map => { + const map = new Map(); + for (const obj of atKey.get(k) ?? []) { + for (const field of obj.fields()) { + const column = resolveColumnName(field); + if (!map.has(column)) map.set(column, { owner: obj, field }); + } + } + return map; + }; + + const tables: DocsViewTable[] = []; + const keys = new Set(); + for (const [entity, source] of entities) { + const identity = entity.primaryIdentity(); + const pkNames = identity !== undefined ? identityFields(identity) : []; + const gen = identity?.attr(IDENTITY_ATTR_GENERATION); + const generation = typeof gen === "string" ? gen : ""; + const raw: RawColumn[] = []; + for (const field of entity.fields()) { + if (isDerived(field)) continue; + const isPk = pkNames.includes(field.name); + raw.push(...fieldColumns(field, isPk, isPk ? generation : "")); + } + if (entity.attr(OBJECT_ATTR_DISCRIMINATOR) !== undefined) { + const existing = new Set(raw.map((c) => c.name)); + const baseFields = new Set(entity.fields().map((f) => f.name)); + for (const sub of tphConcreteSubtypes(entity, objects)) { + for (const field of sub.fields()) { + if (baseFields.has(field.name) || isDerived(field)) continue; + const col = rawColumn(field, false, "", resolveColumnName(field)); + if (existing.has(col.name)) continue; + col.nullable = true; // a row of any other subtype stores NULL here + raw.push(col); + existing.add(col.name); + } + } + } + const schema = schemaOf(source); + const k = key(source.physicalName, schema); + const mapping = fieldOf(k); + const columns: DocsViewColumn[] = raw.map((c) => { + const m = mapping.get(c.name); + return { + name: c.name, + field: m === undefined ? null : links.member(m.owner, m.field), + nullable: c.nullable, + identity: c.identity, + description: c.description, + sqlType: null, + default: null, + }; + }); + tables.push({ + name: source.physicalName, + schema, + declaredBy: links.node(entity), + objects: (atKey.get(k) ?? []).filter((o) => !o.isAbstract).map((o) => links.node(o)), + description: description(entity), + primaryKey: pkNames.map((n) => columnOf(entity, n)), + columns, + foreignKeys: foreignKeys(entity, objects, tableOf), + indexes: null, + checks: null, + }); + keys.add(k); + } + + const views: DocsViewStoredView[] = []; + for (const obj of objects) { + if (obj.isAbstract) continue; + const source = primaryRdbSource(obj); + if (source === undefined || source.effectiveKind !== SOURCE_KIND_VIEW) continue; + const schema = schemaOf(source); + const k = key(source.physicalName, schema); + if (keys.has(k)) continue; + keys.add(k); + const columns: DocsViewViewColumn[] = [...fieldOf(k).entries()].map(([name, m]) => ({ + name, + field: links.member(m.owner, m.field), + })); + views.push({ + name: source.physicalName, + schema, + declaredBy: links.node(obj), + objects: (atKey.get(k) ?? []).filter((o) => !o.isAbstract).map((o) => links.node(o)), + columns, + }); + } + + tables.sort((a, b) => byCodeUnit(a.name, b.name)); + views.sort((a, b) => byCodeUnit(a.name, b.name)); + return { physical: false, dialect: "", tables, views }; +} diff --git a/server/typescript/packages/metadata/src/docs-view/types.ts b/server/typescript/packages/metadata/src/docs-view/types.ts index 1909a9658e..c7d6f6caa6 100644 --- a/server/typescript/packages/metadata/src/docs-view/types.ts +++ b/server/typescript/packages/metadata/src/docs-view/types.ts @@ -286,6 +286,93 @@ export interface DocsViewSlice { nodes: string[]; } +/** A column of a table the model declares. */ +export interface DocsViewColumn { + name: string; + /** The field that declares it (the first writer on a shared table; its `kind` is the + * declared `field.`); null for a column no field names by itself (a member of a + * flattened value object). */ + field: DocsViewLink | null; + nullable: boolean; + /** `increment` or `uuid` on a generated primary-key column; "" otherwise. */ + identity: string; + description: string; + /** Physical: the dialect's SQL type. Null unless `storage.physical`. */ + sqlType: string | null; + /** Physical: the column default as SQL. Null unless `storage.physical` (and when none). */ + default: string | null; +} + +export interface DocsViewForeignKey { + columns: string[]; + refTable: string; + refColumns: string[]; + /** Physical: the constraint name. Null unless `storage.physical`. */ + name: string | null; + /** Physical: the referential actions. Null unless `storage.physical` (and when none). */ + onDelete: string | null; + onUpdate: string | null; +} + +/** Physical: an index on a table. */ +export interface DocsViewIndex { + name: string; + columns: string[]; + unique: boolean; +} + +/** Physical: a check constraint on a table. */ +export interface DocsViewCheck { + name: string; + expression: string; +} + +export interface DocsViewTable { + name: string; + /** The `@schema` as declared; "" without one. */ + schema: string; + /** The object whose source declares the table. */ + declaredBy: DocsViewLink; + /** Every concrete object stored in it (the declaring one and its TPH subtypes), in + * declaration order. */ + objects: DocsViewLink[]; + description: string; + /** Column names. */ + primaryKey: string[]; + /** In declaration order; a TPH subtype's own columns follow its base's. */ + columns: DocsViewColumn[]; + foreignKeys: DocsViewForeignKey[]; + /** Physical. Null unless `storage.physical`. */ + indexes: DocsViewIndex[] | null; + checks: DocsViewCheck[] | null; +} + +export interface DocsViewViewColumn { + name: string; + /** The field that declares it (the first writer). */ + field: DocsViewLink | null; +} + +export interface DocsViewStoredView { + name: string; + schema: string; + declaredBy: DocsViewLink; + objects: DocsViewLink[]; + columns: DocsViewViewColumn[]; +} + +/** The tables and views the model declares, named by the port's naming helpers. */ +export interface DocsViewStorage { + /** The physical facts are filled: the TypeScript run had the expected schema. */ + physical: boolean; + /** The dialect of those facts; "" unless `physical`. */ + dialect: string; + /** Sorted by name. */ + tables: DocsViewTable[]; + /** Sorted by name. */ + views: DocsViewStoredView[]; +} + export interface DocsView { format: typeof DOCS_VIEW_FORMAT; sources: DocsViewSources; @@ -296,4 +383,5 @@ export interface DocsView { requirements: DocsViewRequirement[]; advisories: DocsViewAdvisory[]; slices: DocsViewSlice[]; + storage: DocsViewStorage; } diff --git a/server/typescript/packages/sdk/src/agent-context/agent-pages.ts b/server/typescript/packages/sdk/src/agent-context/agent-pages.ts new file mode 100644 index 0000000000..366eab14f3 --- /dev/null +++ b/server/typescript/packages/sdk/src/agent-context/agent-pages.ts @@ -0,0 +1,66 @@ +// The always-on file's pointer at the pages `meta gen` writes for a coding agent. +// +// The pointer is there only when the pages are: a project that wires no agent-pages generator +// is never told to read a file that does not exist. What is wired is read off the committed +// `.metaobjects/.gen-state/.hashes/` (one file per package, keyed by the project-relative path +// of every file a run wrote), which every port's `gen` writes, so the check needs no config +// evaluation and reads the same in every port. Python's init renders the same section from the +// same template (`agent_context/agent_pages.py`); fixtures/agent-pages-pointer/ pins both. + +import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +/** The template of the section, under the content tree's `templates/`. */ +export const AGENT_PAGES_TEMPLATE = "agent-pages.md.mustache"; + +/** The heading the section is inserted above: the always-on file's rules. */ +export const AGENT_PAGES_ANCHOR = "\n## Rules\n"; + +/** Each agent page, by the path it ends with, and when to read it. In the order they are listed. */ +export const AGENT_PAGES: readonly { readonly suffix: string; readonly when: string }[] = [ + { suffix: "agent/schema.md", when: "before you touch persistence: tables, columns, keys and views" }, + { suffix: "agent/ui.md", when: "before you touch a form or a grid" }, + { suffix: "agent/requirements.md", when: "before you add or change a capability" }, + { suffix: "AGENT-API.md", when: "before you call or change the generated API" }, + { suffix: "requirements.toon", when: "the requirement ledger, in the form a tool reads" }, +]; + +const HASHES_DIR = join(".metaobjects", ".gen-state", ".hashes"); + +function pageIndex(path: string): number { + return AGENT_PAGES.findIndex((p) => path === p.suffix || path.endsWith(`/${p.suffix}`)); +} + +/** The agent pages the project's last `gen` wrote, as project-relative paths, in page order + * and then by path. Empty when nothing records one. */ +export function wiredAgentPages(cwd: string): string[] { + const dir = join(cwd, HASHES_DIR); + if (!existsSync(dir)) return []; + const found = new Set(); + for (const name of readdirSync(dir).filter((n) => n.endsWith(".json")).sort()) { + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(join(dir, name), "utf8")); + } catch { + continue; // an unreadable hashes file is `gen`'s to report, not this pointer's + } + if (typeof parsed !== "object" || parsed === null) continue; + for (const path of Object.keys(parsed)) if (pageIndex(path) >= 0) found.add(path); + } + return [...found].sort((a, b) => pageIndex(a) - pageIndex(b) || (a < b ? -1 : a > b ? 1 : 0)); +} + +/** The section for `pages`, from `template`; "" when there are none. */ +export function renderAgentPagesSection(template: string, pages: readonly string[]): string { + if (pages.length === 0) return ""; + const list = pages.map((p) => `- \`${p}\`: ${AGENT_PAGES[pageIndex(p)]!.when}.`).join("\n"); + return template.replace("{{pageList}}", list); +} + +/** `alwaysOn` with `section` inserted above its rules. Throws when the anchor is missing. */ +export function withAgentPagesSection(alwaysOn: string, section: string): string { + if (section === "") return alwaysOn; + const at = alwaysOn.indexOf(AGENT_PAGES_ANCHOR); + if (at < 0) throw new Error(`agent-context: the always-on file has no "${AGENT_PAGES_ANCHOR.trim()}" heading to place the agent pages above`); + return `${alwaysOn.slice(0, at + 1)}${section}${alwaysOn.slice(at + 1)}`; +} diff --git a/server/typescript/packages/sdk/src/agent-context/assemble.ts b/server/typescript/packages/sdk/src/agent-context/assemble.ts index 9c91f03d1a..b72af6a324 100644 --- a/server/typescript/packages/sdk/src/agent-context/assemble.ts +++ b/server/typescript/packages/sdk/src/agent-context/assemble.ts @@ -139,6 +139,9 @@ function applyTemplate( * `skillsDir` is where the skills install (default {@link DEFAULT_SKILLS_DIR}); the always-on * text names it, so an assistant that does not load skills can open them by path. */ +/** Where the always-on file goes, relative to the project root. */ +export const ALWAYS_ON_PATH = ".metaobjects/AGENTS.md"; + export function assemble(opts: { contentRoot: string; stack: Stack; docsRef?: string; skillsDir?: string }): AssembledFile[] { const { contentRoot, stack } = opts; const docsRef = opts.docsRef ?? "main"; @@ -161,7 +164,7 @@ export function assemble(opts: { contentRoot: string; stack: Stack; docsRef?: st // dialect; any other project migrates with its own tool. { migration: stack.migration }, ); - out.push({ path: ".metaobjects/AGENTS.md", contents: alwaysOn }); + out.push({ path: ALWAYS_ON_PATH, contents: alwaysOn }); // 2. Skills: body + only the references whose token is in the stack. for (const skill of SKILL_NAMES) { diff --git a/server/typescript/packages/sdk/src/agent-context/index.ts b/server/typescript/packages/sdk/src/agent-context/index.ts index 6e4ecf9f29..3c05323c37 100644 --- a/server/typescript/packages/sdk/src/agent-context/index.ts +++ b/server/typescript/packages/sdk/src/agent-context/index.ts @@ -1,5 +1,6 @@ export * from "./types.js"; export * from "./resolve.js"; +export * from "./agent-pages.js"; export * from "./assemble.js"; export * from "./content-root.js"; export * from "./scaffold.js"; diff --git a/server/typescript/packages/sdk/src/agent-context/shipped.ts b/server/typescript/packages/sdk/src/agent-context/shipped.ts index 37708a0bd7..6076f8c5b0 100644 --- a/server/typescript/packages/sdk/src/agent-context/shipped.ts +++ b/server/typescript/packages/sdk/src/agent-context/shipped.ts @@ -9,7 +9,10 @@ // `docsLinkPrefix + + "/"` in every file (what `pinDocsRefs` does), and // writes each file at its `path`. import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { DOCS_DEFAULT_REF, DOCS_REPO_URL } from "@metaobjectsdev/metadata"; +import { AGENT_PAGES_TEMPLATE } from "./agent-pages.js"; import { assemble } from "./assemble.js"; import { makeStack } from "./resolve.js"; import { @@ -103,6 +106,10 @@ export interface ShippedManifest { readonly docsLinkPrefix: string; /** The directory the skills' paths start with. */ readonly skillsDir: string; + /** The stored file holding the template of the always-on file's agent-pages section + * (`agent-pages.ts`): a port inserts it above the rules when the project's `.hashes/` + * record an agent page, and fixtures/agent-pages-pointer/ pins what it renders. */ + readonly agentPagesTemplate: string; readonly stacks: readonly ShippedStack[]; } @@ -140,11 +147,15 @@ export function buildShippedAgentContext(contentRoot: string): ShippedAgentConte }); stacks.push({ id: shippedStackId(stack), servers: stack.servers, clients: stack.clients, migration, files: refs }); } + const pagesTemplate = readFileSync(join(contentRoot, "templates", AGENT_PAGES_TEMPLATE), "utf8"); + const agentPagesTemplate = storedName(pagesTemplate); + files.set(agentPagesTemplate, pagesTemplate); const manifest: ShippedManifest = { schema: SHIPPED_AGENT_CONTEXT_SCHEMA, docsRef: DOCS_DEFAULT_REF, docsLinkPrefix: `${DOCS_REPO_URL}/blob/`, skillsDir: DEFAULT_SKILLS_DIR, + agentPagesTemplate, stacks, }; const sorted = new Map([...files.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))); diff --git a/server/typescript/packages/sdk/test/agent-context/agent-pages.test.ts b/server/typescript/packages/sdk/test/agent-context/agent-pages.test.ts new file mode 100644 index 0000000000..09e043e943 --- /dev/null +++ b/server/typescript/packages/sdk/test/agent-context/agent-pages.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, test } from "bun:test"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { + AGENT_PAGES_TEMPLATE, + renderAgentPagesSection, + wiredAgentPages, + withAgentPagesSection, +} from "../../src/agent-context/agent-pages.js"; + +const REPO = join(import.meta.dir, "..", "..", "..", "..", "..", ".."); +const CASES = join(REPO, "fixtures", "agent-pages-pointer", "cases"); +const TEMPLATE = readFileSync(join(REPO, "agent-context", "templates", AGENT_PAGES_TEMPLATE), "utf8"); + +describe("agent-pages-pointer corpus", () => { + for (const name of readdirSync(CASES).sort()) { + test(name, () => { + const dir = join(CASES, name); + const section = renderAgentPagesSection(TEMPLATE, wiredAgentPages(dir)); + expect(section).toBe(readFileSync(join(dir, "expected-section.md"), "utf8")); + }); + } +}); + +describe("withAgentPagesSection", () => { + test("inserts above the rules and leaves the rest", () => { + const file = "# T\n\nintro\n\n## Rules\n\n- a\n"; + expect(withAgentPagesSection(file, "## Pages\n\nx\n\n")).toBe("# T\n\nintro\n\n## Pages\n\nx\n\n## Rules\n\n- a\n"); + }); + test("an empty section leaves the file unchanged", () => { + expect(withAgentPagesSection("no anchor", "")).toBe("no anchor"); + }); + test("a file with no rules heading is refused", () => { + expect(() => withAgentPagesSection("no anchor", "## Pages\n")).toThrow(/Rules/); + }); +}); diff --git a/server/typescript/packages/sdk/test/agent-context/shipped.test.ts b/server/typescript/packages/sdk/test/agent-context/shipped.test.ts index 0732245490..27d2b6d817 100644 --- a/server/typescript/packages/sdk/test/agent-context/shipped.test.ts +++ b/server/typescript/packages/sdk/test/agent-context/shipped.test.ts @@ -92,7 +92,7 @@ describe("the stacks shipped", () => { }); test("a file shared by many stacks is stored once", () => { - const refs = built.manifest.stacks.flatMap((s) => s.files.map((f) => f.file)); + const refs = [...built.manifest.stacks.flatMap((s) => s.files.map((f) => f.file)), built.manifest.agentPagesTemplate]; expect(built.files.size).toBe(new Set(refs).size); expect(built.files.size).toBeLessThan(refs.length / 10); }); From 34dbdc1aa3ad7163b1b9ebb296409f9507b9dabb Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 07:00:42 -0500 Subject: [PATCH 06/21] wip: TS agent-docs model-only schema, requirements.md retired in docs --- changelog.d/agent-pages-every-port.md | 26 ++++++++++ docs/features/cli.md | 13 ++--- docs/features/docs-view.md | 34 +++++++++++++ docs/features/metadata-dependencies.md | 2 +- docs/features/own-your-codegen.md | 6 +-- docs/features/requirements.md | 8 +-- docs/ports/python.md | 3 +- fixtures/docs-page-conformance/README.md | 49 +++++++++++-------- .../cli/test/unit/reporting-inert.test.ts | 8 ++- .../src/generators/agent-docs-file.ts | 14 ++++-- .../codegen-ts/src/reference/agent-docs.ts | 14 ++++-- .../test/agent-docs-surface.test.ts | 6 ++- .../test/reference-byte-identical.test.ts | 4 +- .../test/requirements-file-generator.test.ts | 20 ++------ 14 files changed, 144 insertions(+), 63 deletions(-) create mode 100644 changelog.d/agent-pages-every-port.md diff --git a/changelog.d/agent-pages-every-port.md b/changelog.d/agent-pages-every-port.md new file mode 100644 index 0000000000..46f472786c --- /dev/null +++ b/changelog.d/agent-pages-every-port.md @@ -0,0 +1,26 @@ +- **The agent pages in every port, from the docs view.** `requirements.toon`, + `agent/requirements.md` and the model-only `agent/schema.md` are now written by C#, Java, + Kotlin, Python, Rust and TypeScript alike: each port's `requirements` and `agent-docs` + generators build the page data from its own docs view and render the shared + `templates/requirements/` and `templates/agent/` Mustache pages, byte for byte what + `fixtures/docs-page-conformance/` pins. A TypeScript project with no dialect now gets the + model-only `agent/schema.md` too (it used to get no schema page); with a dialect it keeps the + physical page. `agent/ui.md` stays TypeScript's. + + The docs view gains a `storage` section (`docs/features/docs-view.md`): every table and view + the model stores into, its columns (names from the port's naming helpers, each linked to its + field), keys and foreign keys. The physical facts (SQL types, defaults, indexes, checks, + constraint names and actions) are `null` outside a TypeScript run with a dialect, which fills + them. `explorer.json` carries the new key in every port. + + **Retired: the human `requirements.md` page.** The `requirements` generator writes only + `requirements.toon`; people read the ledger in the explorer (`docs-site`), and agents read it + embedded in `agent/requirements.md`. Upgrading: the next `gen` no longer writes + `requirements.md`; delete the committed copy (and its `.hashes/` entry goes with the run). + + **The always-on agent file points at the agent pages, only when they exist.** `meta init` + (and `--refresh-docs`) and the C#, Java and Python agent-docs commands now add a "Pages + generated for this project" section to `.metaobjects/AGENTS.md`, naming each agent page the + project's last `gen` wrote (read from the committed `.metaobjects/.gen-state/.hashes/`) and + when to read it. A project that wires none of them gets the file unchanged. Refresh the agent + files after wiring `agent-docs`, `api-docs` or `requirements` for the first time. diff --git a/docs/features/cli.md b/docs/features/cli.md index c222826160..b41e41c39a 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -365,7 +365,7 @@ documentation never lands in the code's output directory by default. |---|---|---| | `docs` | `docsFile()` | The NEUTRAL per-entity + per-template pages plus a README index, with the ER diagrams. Makes no language assumption at all (ADR-0020). | | `api-docs` | `apiDocsFile()` | The generated SDK reference under `api/` — types, endpoints, filter operators — plus `AGENT-API.md`, its condensed agent form. | -| `requirements` | `requirementsFile()` | The declared ledger, as `requirements.md` + `requirements.toon`; nothing for a model with no `requirement.*` node. | +| `requirements` | `requirementsFile()` | The declared ledger, as `requirements.toon` (people read it in the explorer, `docs-site`); nothing for a model with no `requirement.*` node. | | `agent-docs` | `agentDocsFile()` | Three pages an agent reads BEFORE touching a tier (below), under `agent/`. | | `metamodel-docs` | `metamodelDocsFile()` | The reference of the BUILT-IN metamodel (every registered type, subtype and attribute), not your model, under `metamodel/`. Its rendered form is published at . | | `docs-site` | `docsSiteFile()` | The HTML site under `site/`: the model explorer by default ([explorer-site.md](explorer-site.md)), the earlier site with `site: "classic"`; `meta eject docs-site` copies its templates and assets to `codegen/docs-site/` for you to change. | @@ -408,19 +408,20 @@ Two properties worth knowing: **Every page is derived from a builder that already exists**, and none has a derivation of its own. The schema page reads the expected-schema snapshot `meta migrate` diffs and emits -from; the UI page reads the same descriptor emitted as the `` const that -`useEntityForm` consumes at runtime; the requirements page reads the same walk the ledger -surface and the generated test stubs are built on. A page an agent is told to trust has to +from (with no dialect, it is the model-only page every port writes, read off the docs view's +`storage` section); the UI page reads the same descriptor emitted as the `` const that +`useEntityForm` consumes at runtime; the requirements page reads the docs view's requirements, as the ledger surface does in every +port. A page an agent is told to trust has to be true, and this is the only way to keep three more of them true. **An empty page is no file.** Each renders nothing when its tier has nothing to describe — -no physical schema, no generated UI, no ledger — so a project sees only the pages it has +no table or view, no generated UI, no ledger — so a project sees only the pages it has content for, and one with none sees no `agent/` directory at all. Physical names, the dialect and view dispatch all come from `metaobjects.config.ts`, which `meta gen` always has. The neutral model pages make no use of them and stay neutral. `agent/schema.md` asks the same guard `meta gen` does — a model that emits database code must declare a `dialect`, and -`DEFAULT_DIALECT` is inert — so the page is skipped, with the runner's own message, exactly +`DEFAULT_DIALECT` is inert — so the physical page is skipped, with the runner's own message, exactly when `meta gen` would refuse the model, and also when the expected schema cannot be built at all (a primary-key move, a duplicate physical name: conditions `meta migrate` reports properly, and docs must not be the command that fails on them). diff --git a/docs/features/docs-view.md b/docs/features/docs-view.md index 0c8695d2bf..9a36bcd1a5 100644 --- a/docs/features/docs-view.md +++ b/docs/features/docs-view.md @@ -126,6 +126,7 @@ interface DocsView { requirements: DocsViewRequirement[]; advisories: DocsViewAdvisory[]; slices: DocsViewSlice[]; + storage: DocsViewStorage; } ``` @@ -264,6 +265,39 @@ Named node sets a map view opens on, all derived, each `{ id, kind, anchor, node - `prompt:`: one per template. It holds the template and what its own attributes reference (its payload and reply). +### `storage` + +Where the model's objects are stored, as names: what the model-only `agent/schema.md` page is +built from in every port (`fixtures/docs-page-conformance/`). + +```ts +interface DocsViewStorage { + physical: boolean; // true only when TypeScript filled the physical facts below + dialect: string; // the dialect they are for, or "" + tables: DocsViewTable[]; // sorted by name + views: DocsViewStoredView[]; // sorted by name +} +``` + +- **A table** is `{ name, schema, declaredBy, objects, description, primaryKey, columns, + foreignKeys, indexes, checks }`: one per concrete object whose primary source is a writable, + managed table. A TPH subtype shares its base's table and adds its columns there, nullable; + an `@unmanaged` table is only a foreign-key target. `declaredBy` links the declaring object, + `objects` every concrete object stored there. +- **A column** is `{ name, field, nullable, identity, description, sqlType, default }`. `field` + links the field's member row (first writer wins on a shared table); `nullable` is false for a + primary-key column and a required field; `identity` is the increment kind of a generated key. +- **A foreign key** is `{ columns, refTable, refColumns, name, onDelete, onUpdate }`, from each + `identity.reference` (one with `@enforce: false` is left out). +- **A view** is `{ name, schema, declaredBy, objects, columns }`, a column being `{ name, field }`; + the lineage is read from the linked field's `origin.*` member. + +Table, view and column names come from each port's own naming helpers (`naming` in +`.metaobjects/config.json`). The physical facts (`sqlType`, `default`, `indexes`, `checks`, a +foreign key's `name` and actions) are `null` in every port. The TypeScript `docs-site` run fills +them from the expected schema `meta migrate` diffs against when the project has a dialect, and +sets `physical` and `dialect`; the committed cases are built without one. + ## Verified by - [`fixtures/explorer-conformance/`](../../fixtures/explorer-conformance/): each case's diff --git a/docs/features/metadata-dependencies.md b/docs/features/metadata-dependencies.md index c2bd6f0308..47f2e46caf 100644 --- a/docs/features/metadata-dependencies.md +++ b/docs/features/metadata-dependencies.md @@ -407,7 +407,7 @@ A dependency published with `requirements: true` carries its requirements, and t with its model: an overlay of one resolves, and `meta verify` can see it. By default they stay the **publisher's** ledger, not yours. The requirement gate does not check, count, summarise or lint them, the `requirement-tests` generator writes no test for them, and the -requirements pages (`requirementsFile()`, the agent docs' `requirements.md`, an entity page's +requirements pages (`requirementsFile()`'s `requirements.toon`, the agent docs' `agent/requirements.md`, an entity page's "Required by") do not list them. That is the same default as an imported entity's code generation, for the same reason: you did not declare them. diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 940b074fb1..3eb02b36b8 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -290,7 +290,7 @@ it yourself. |---|---|---| | `docs` | which objects and templates get a page, where a page lands, which page template renders, the whole overview page (`renderIndexPage`) | the page payloads (`buildEntityDocData`, `buildTemplateDocData`) and the ER diagram (`renderMermaidErBlock`) | | `api-docs` | which units get a page, where a page lands, whether the index and the agent form (`AGENT-API.md`) are written | the model of the generated API (`buildApiModelForRun`, which also reads the run: layout, `apiPrefix`, whether Hono routes are wired) and its renderers (`renderEntityApiPage`, `renderApiIndex`, `renderAgentApi`) | -| `requirements` | which files the ledger becomes and where they land (`requirements.md`, `requirements.toon`); a project with no `requirement.*` node gets none | the two page builders (`requirements-markdown`, `requirements-toon`) and the projection they read (`requirements-view`) | +| `requirements` | where the ledger lands (`requirements.toon`); a project with no `requirement.*` node gets none | the page builder (`requirements-toon`) and the rows it reads off the docs view (`requirements-view`, `docs-view-pages`) | | `agent-docs` | which of the three pages are written and where | the three page builders (`agent-schema-page`, which also walks the model for the column-to-field map, lineage, relationships and enums; `agent-ui-page`; `agent-requirements-page`) | | `metamodel-docs` | which pages are written and where they land | the page render call (`renderDocPage`); each page's data comes from `coreMetamodelDocsPages` in `@metaobjectsdev/metadata`, which is core, and its layout from the shared `metamodel/*.mustache` templates | @@ -299,8 +299,8 @@ package. To change the wording of a model page you need no eject: put a file of name in your project (`templates/docs/entity-page.md.mustache` or `template-page.md.mustache`), or point `docsFile({ templates })` at another directory; it wins over the packaged one. The requirements and agent pages work the same way: -`templates/requirements/requirements.md.mustache` and `requirements.toon.mustache` -(`requirementsFile({ templates })`), and `templates/agent/schema.md.mustache` and +`templates/requirements/requirements.toon.mustache` (`requirementsFile({ templates })`), and +`templates/agent/schema.md.mustache` and `requirements.md.mustache` (`agentDocsFile({ templates })`; its embedded ledger is the `requirements/requirements.md` template). The templates and the data they are fed are pinned in `fixtures/docs-page-conformance/`; which ports run that corpus is in [CONFORMANCE.md](../CONFORMANCE.md). diff --git a/docs/features/requirements.md b/docs/features/requirements.md index ab7198d178..e59a605ac8 100644 --- a/docs/features/requirements.md +++ b/docs/features/requirements.md @@ -262,9 +262,11 @@ describes **the revival**, which is the thing a future reader is about to propos governs nothing. **One honest limit.** 19 of 40 is under half, and the guardrail only fires if something routes -an agent to the ledger. The requirement ledger (`requirementsFile()`) and the agent pages -(`agentDocsFile()`) carry retired entries; if -your agents never read it, restoring the entry buys you a coin flip. Point at it. +an agent to the ledger. The requirement ledger (`requirementsFile()`'s `requirements.toon`), +the explorer (`docs-site`) and the agent pages (`agentDocsFile()`) carry retired entries, in +every port; if your agents never read them, restoring the entry buys you a coin flip. Point at +them: once a `gen` has written the agent pages, the always-on `.metaobjects/AGENTS.md` that +`meta init --refresh-docs` (or your port's agent-docs command) writes names each one. > **`@verifiedBy` was retired in `0.24.0`, and `verify` no longer looks at your tests.** It asked > you to name a test and then checked only that the **name** occurred somewhere in the test diff --git a/docs/ports/python.md b/docs/ports/python.md index 1400063391..6e584dcc11 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -1086,9 +1086,10 @@ definitions, and import lines are stable. | Migrations | Your own tool (Alembic, say) handed `meta schema`, or the Node reference helper (ADR-0015, Amendment 2) — no Python `migrate` command; the canonical `schema.postgres.sql` is the expected schema | | Drift verify | Yes — template / payload drift (`metaobjects verify`); `verify --codegen` regenerates the config's list and diffs each target's `outDir` | | API reference docs | Yes — `api-docs` in a target's `generators`, options in the top-level `apiDocs` block (`apiSubDir`, `projectName`, `modelBaseUrl`); `metaobjects docs` was removed in 1.1.0 ([migration](../features/migrations/docs-are-generators.md#python)) | -| Requirements and agent pages | Yes — `requirements` (`requirements.md`, `requirements.toon`) and `agent-docs` (`agent/requirements.md` and the model-only `agent/schema.md`: no SQL types, defaults, indexes or checks; `agent/ui.md` is TypeScript-only) in a target's `generators`, rendered from the shared templates bundled in the package; a same-named file under the project's templates directory overrides a page; both ejectable | +| Requirements and agent pages | Yes — `requirements` (`requirements.toon`; the human `requirements.md` page is retired, the explorer replaces it) and `agent-docs` (`agent/requirements.md`, which embeds the ledger, and the model-only `agent/schema.md`: no SQL types, defaults, indexes or checks; `agent/ui.md` is TypeScript-only) in a target's `generators`, each rendered from the shared templates bundled in the package over the docs view (`build_docs_view`, including its `storage` section of tables and views named by this port's naming helpers; gated by `fixtures/docs-page-conformance/`); a same-named file under the project's templates directory overrides a page; both ejectable | | Metamodel reference | Yes — `metamodel-docs` in a target's `generators` (`INDEX.md`, `providers.md` and `types/.md` under `metamodel/`; option `subDir`), rendered from the shared templates bundled in the package over the port's own registry manifest and embedded provider definitions; reads no model objects; a same-named file under the project's templates directory overrides a page; ejectable | | Model explorer | Yes, with no Node — `docs-site` in a target's `generators`: under `/` (default `site`) it writes the explorer app (`index.html` and `assets/`, the same bytes in every port, shipped as package data), `explorer.json` (the docs view, built from the model the run loaded by `metaobjects.docs_view.build_docs_view`; byte-identical to TypeScript's for the same inputs, gated by `fixtures/explorer-conformance/`), `explorer-model.js` and `explorer-stamp.js`. Each object lists the files generated for it (`generatedBy`, `sourceNode`): the run's own, laid over what the committed hash manifest records. The runner runs it after every other generator, so a write run and `verify --codegen` list the same files. Options: `subDir`, `title` (default: the project directory's name), `stamp` (footer text, default none), `prompts` (a directory of prompt `.mustache` sources beside the metadata and `templates/`), `verifyFile` (a `verify --format json` payload from the Node CLI, for the requirement verdicts), `routesFile` (the routes the application mounts, `[{ node, method, path }]`, `node` a resolution key). An owned theme under `codegen/docs-site/` (`assets/explorer.css`, `assets/explorer.js`, `templates/explorer-*.mustache`) wins over the packaged one. Not ejectable: the builder is engine, the theme is what you own. The page-per-screen static export and the classic site stay TypeScript's | +| Always-on pointer | Yes — `metaobjects agent-docs` inserts a section above `## Rules` in `.metaobjects/AGENTS.md` naming the agent pages (`agent/schema.md`, `agent/requirements.md`, `requirements.toon`, ...) that the project's committed `.metaobjects/.gen-state/.hashes/` record; no recorded page, no change (`fixtures/agent-pages-pointer/`) | | Docs view endpoint | `META_DOCS_ROUTE_PATH` (`/_meta/docs`), `meta_docs_json(root, routes=None)` and `meta_docs(root, routes=None)` in `metaobjects` (like `/_meta`, a framework-free helper, not a mount): the body is the docs view of the loaded model alone, byte-identical to every other port's (`fixtures/explorer-conformance/model-alone/`); `meta_docs` builds it once with a strong `ETag` and `matches(if_none_match)` for the `304`. Contract: [metadata-api.md](../features/metadata-api.md#the-docs-view-endpoint-get-_metadocs) | | Requirement gate + requirement tests | Yes (`metaobjects verify`, on every run; `requirement-tests` emits pytest and is ejectable) | | Business-rules gate (ADR-0066, experimental) | Yes (`metaobjects verify`, on every run; see [business rules](../features/business-rules.md)) | diff --git a/fixtures/docs-page-conformance/README.md b/fixtures/docs-page-conformance/README.md index 909040d206..894f1d8dd9 100644 --- a/fixtures/docs-page-conformance/README.md +++ b/fixtures/docs-page-conformance/README.md @@ -1,8 +1,14 @@ # docs-page-conformance -The shared corpus for the documentation pages every port writes from the requirement -ledger and the model: `requirements.md`, `requirements.toon`, `agent/requirements.md` and -the **model-only** `agent/schema.md`. +The shared corpus for the documentation pages every port writes from its docs view +(`docs/features/docs-view.md`): `requirements.toon`, `agent/requirements.md` and the +**model-only** `agent/schema.md`. Each port's builders read the view and nothing else: the +requirement rows from its `requirements`, the node index from each requirement's resolved +`implementedBy`, and the schema from its `storage` section plus the members of the nodes it +links (reference: `server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts`). + +The human `requirements.md` page was retired in 1.3.0: people read the ledger in the explorer +(`docs-site`). Its template stays, as the ledger `agent/requirements.md` embeds. **The TypeScript generators are the source of the expected bytes.** A port that disagrees with a case is wrong, not the case. @@ -13,7 +19,7 @@ Every page is a shared Mustache template fed the data a builder computes: | Page | Template (canonical copy) | Data | |---|---|---| -| `requirements.md` | `templates/requirements/requirements.md.mustache` | `data/requirements.md.json` | +| the ledger inside `agent/requirements.md` | `templates/requirements/requirements.md.mustache`, embedded form | `data/ledger.md.json` | | `requirements.toon` | `templates/requirements/requirements.toon.mustache` | `data/requirements.toon.json` | | `agent/requirements.md` | `templates/agent/requirements.md.mustache` | `data/agent-requirements.md.json` | | `agent/schema.md` | `templates/agent/schema.md.mustache` | `data/agent-schema.md.json` | @@ -26,6 +32,7 @@ has two checks: 1. **Builder.** The port's builder, run on `input/`, produces `expected/data/.json` (compare as JSON values). 2. **Page.** Rendering the template with that data produces `expected/` byte for byte. + (The embedded ledger has no page of its own; it is checked inside `agent/requirements.md`.) Under the page data sits one more layer, `expected/rows/`, the rows each builder starts from: @@ -34,30 +41,30 @@ Under the page data sits one more layer, `expected/rows/`, the rows each builder | `rows/requirements.json` | One row per requirement in the ledger, in declaration order: `path`, `depth`, `title`, `subType`, `level`, `status`, `disposition`, `trackedBy`, `statement`, `counterexample`, `description`, `implementedBy` (as written), `claimedConcerns` (the `type.subType` of each target that resolves). Both requirements pages are built from these. | What the docs site's explorer graph holds: the requirement node's attributes plus its verify ledger row | | `rows/schema.json` | The model-only schema: tables (name, schema, description, primary key, columns with `nullable`, `identity` and `description`, foreign keys as columns → table and columns), views (name, schema), and `declaredBy` (each table or view → the declaring object). | A subset of `meta schema --as json` (the `serializeSnapshot` format), the storage lens's input | -These rows are how the 1.3.0 docs-page design pass (D0a) settles the shapes: the docs site -reuses the rows rather than pinning a second shape for the same facts, so a later site lens is -built over these rows, not a new extraction. A port checks its rows first (compare as JSON -values), then its page data, then the bytes. The model-only page data follows from the rows -and the model alone; the TypeScript runner proves it by rebuilding the page from -`rows/schema.json` (`schemaInputFromRows`). `cli/test/docs-page-shapes.test.ts` holds the +Both are read off the docs view: `rows/requirements.json` from its `requirements` +(`requirementRowsFromView`), `rows/schema.json` from its `storage` (`schemaRowsFromView`). A +port checks its rows first (compare as JSON values), then its page data, then the bytes. The +TypeScript runner also holds the view-built rows and page equal to the ones it builds from the +expected schema (`schemaRows`, `agentSchemaPageData` with `physical: false`), so the model-only +page is the physical page less its physical facts. `cli/test/docs-page-shapes.test.ts` holds the requirement rows equal to the docs view's (on `fixtures/explorer-conformance/shop/`) and the schema rows to a subset of `meta schema`'s output. A page the case does not list is a page the port must NOT write: a model with no `requirement.*` node gets neither requirements page, and a model with no table and no view -gets no schema page. +gets no schema page. Every case builds its view with no verify ledger, manifest or routes. Two rules a port must keep. `agent/requirements.md` carries the ledger as its `ledger` value: the `requirements.md` template rendered in its `embedded` form (no `# Requirements` title, every heading one level down, capped at h6), with its trailing line breaks removed. The TOON page ends without a line break; the other pages end with exactly one. -## What a non-TypeScript schema page contains (design call 17) +## What the model-only schema page contains (design call 17) -A port without the expected schema builds the schema page from the model with its own -naming helpers. TypeScript writes the same page with `physical: false`: it builds its input -from the expected schema and then leaves out every fact only that schema knows. The page -contains: +Every port builds this page from its docs view's `storage` section, whose table and column +names come from the port's own naming helpers. TypeScript writes it the same way when the +project has no dialect, and with a dialect writes the physical page from the expected schema +instead. The page contains: - **Tables**: one per object whose primary source is a table in the schema (abstract bases and sourceless values have none; a TPH subtype shares its base's table and adds its own @@ -100,7 +107,9 @@ the project's own migration tool, from the schema `meta schema` prints. A case s - TypeScript: `server/typescript/packages/cli/test/docs-page-conformance.test.ts`. Regenerate with `UPDATE_DOCS_PAGE_FIXTURES=1 bun test test/docs-page-conformance.test.ts` from that package, and review the diff: it is the cross-port contract. -- Python: `server/python/tests/conformance/test_docs_page_conformance.py` (rows, page data, - then the bytes the `requirements` and `agent-docs` generators write). -- C#, Java (Kotlin through Java) and Rust: their page generators are planned and will run - every case. +- Python: `server/python/tests/conformance/test_docs_page_conformance.py`. +- C#: `server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs`. +- Java and Kotlin: `server/java/codegen-base/src/test/java/com/metaobjects/generator/docs/DocsPageConformanceTest.java`. +- Rust: `server/rust/metaobjects-codegen/tests/docs_page_conformance.rs`. + +Each checks rows, page data, then the bytes its `requirements` and `agent-docs` generators write. diff --git a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts index fdfba074e6..200f369513 100644 --- a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts +++ b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts @@ -189,6 +189,8 @@ const BARREL = `${OUT}/index.ts`; /** The agent UI page, which `agent-docs` writes when the run also wires the client tier. It * is one page for the whole model, so a served report adds its section to it. */ const AGENT_UI_PAGE = `${OUT}/agent/ui.md`; +/** The model-only schema page (no dialect in this run): a served report adds its view. */ +const AGENT_SCHEMA_PAGE = `${OUT}/agent/schema.md`; /** The OpenAPI document, one for the whole model, so a served report adds to it. */ const OPENAPI_DOC = `${OUT}/openapi.json`; /** The client UI generators that emit NOTHING for a report: a report has a list hook and no @@ -408,7 +410,7 @@ describe("FR-044 a sourceless report is inert; a served report emits exactly its expect(expected[""]).toBeUndefined(); expect(actual[""]).toBeUndefined(); expect(Object.keys(expected).length).toBeGreaterThan(10); - expectOnlyAdds(expected, actual, Object.values(ADDED_FOR_WITH).flat(), [AGENT_UI_PAGE, OPENAPI_DOC, ...Object.values(SERVICE_GROWS).flat()]); + expectOnlyAdds(expected, actual, Object.values(ADDED_FOR_WITH).flat(), [AGENT_UI_PAGE, AGENT_SCHEMA_PAGE, OPENAPI_DOC, ...Object.values(SERVICE_GROWS).flat()]); // The agent UI page moves by the served report's section alone: every line it had is // still there, in order, and the section names the report. const before = expected[AGENT_UI_PAGE]!.split("\n"); @@ -418,6 +420,10 @@ describe("FR-044 a sourceless report is inert; a served report emits exactly its expect(kept).toBe(before.length); expect(after.filter((l) => !before.includes(l)).join("\n")).toContain("StoreTotals"); for (const name of SOURCELESS_REPORTS) expect(actual[AGENT_UI_PAGE]).not.toContain(name); + // The schema page gains the served report's view, and nothing names a sourceless one. + expect(actual[AGENT_SCHEMA_PAGE]).toContain("`v_store_totals`"); + expect(expected[AGENT_SCHEMA_PAGE]).not.toContain("v_store_totals"); + for (const name of SOURCELESS_REPORTS) expect(actual[AGENT_SCHEMA_PAGE]).not.toContain(name); // In the full suite the barrel re-exports the report's modules. expect(actual[BARREL]).toContain("StoreTotals"); expect(expected[BARREL]).not.toContain("StoreTotals"); diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts b/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts index 5988cf8dc4..2e2a75e8f9 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts @@ -40,6 +40,8 @@ import { physicalNamingGuideUrl } from "@metaobjectsdev/metadata/release-docs"; import { physicalNamingOf, physicalNamingRemovedMessage } from "@metaobjectsdev/metadata"; import type { EmittedFile, Generator, GeneratorFactory } from "../generator.js"; import { renderAgentSchemaPage } from "./agent-schema-page.js"; +import { renderAgentSchemaPageFromView } from "./docs-view-pages.js"; +import { buildDocsView } from "@metaobjectsdev/metadata"; import { renderAgentUiPage } from "./agent-ui-page.js"; import { renderAgentRequirementsPage } from "./agent-requirements-page.js"; import type { AgentSchemaInput } from "./agent-schema-input.js"; @@ -57,8 +59,8 @@ export interface AgentDocsFileOpts { /** * The physical schema, with its resolvers injected by whoever owns them. Default: the one * `meta gen` builds with the project's dialect and column naming (`ctx.docs.agentSchema`). - * ABSENT both ways is a supported state: a project with no physical schema gets no schema - * page rather than a page of unknowns. + * ABSENT both ways (no dialect), the page is the model-only one every port writes, built + * from the docs view. */ schema?: AgentSchemaInput; /** Directory whose `templates/agent/{schema,requirements}.md.mustache` (and @@ -93,8 +95,12 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G // ---- schema.md // The model walk (column → declaring field, view lineage, relationships, enums) is // the page builder's; this passes it the model, the schema and the naming. - if (schemaInput !== undefined) { - const content = renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { provider }); + { + // With no expected schema (no dialect, so no `meta migrate` either), the model-only + // page every port writes, read off the docs view. + const content = schemaInput !== undefined + ? renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { provider }) + : renderAgentSchemaPageFromView(buildDocsView({ root: ctx.loadedRoot }), false, provider); if (content !== "") files.push({ path: `${dir}/schema.md`, content }); } diff --git a/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts b/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts index e4426ee83c..09d2fe67af 100644 --- a/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts +++ b/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts @@ -56,6 +56,8 @@ import { DOCS_TARGET_NAME, } from "@metaobjectsdev/codegen-ts/engine"; import { renderAgentSchemaPage } from "../generators/agent-schema-page.js"; +import { renderAgentSchemaPageFromView } from "../generators/docs-view-pages.js"; +import { buildDocsView } from "@metaobjectsdev/metadata"; import { renderAgentUiPage } from "../generators/agent-ui-page.js"; import { renderAgentRequirementsPage } from "../generators/agent-requirements-page.js"; @@ -69,8 +71,8 @@ export interface AgentDocsFileOpts { target?: string; /** * The physical schema, with its resolvers injected by whoever owns them. Default: the one - * `meta gen` builds (`ctx.docs.agentSchema`). ABSENT both ways is a supported state: a - * project with no physical schema gets no schema page rather than a page of unknowns. + * `meta gen` builds (`ctx.docs.agentSchema`). ABSENT both ways (no dialect), the page is the + * model-only one every port writes, built from the docs view. */ schema?: AgentSchemaInput; /** Directory whose `templates/agent/{schema,requirements}.md.mustache` (and @@ -105,8 +107,12 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G // ---- schema.md // The model walk (column → declaring field, view lineage, relationships, enums) is // the page builder's; this passes it the model, the schema and the naming. - if (schemaInput !== undefined) { - const content = renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { provider }); + { + // With no expected schema (no dialect, so no `meta migrate` either), the model-only + // page every port writes, read off the docs view. + const content = schemaInput !== undefined + ? renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { provider }) + : renderAgentSchemaPageFromView(buildDocsView({ root: ctx.loadedRoot }), false, provider); if (content !== "") files.push({ path: `${dir}/schema.md`, content }); } diff --git a/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts b/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts index 14bfffbdd4..fa8e88c400 100644 --- a/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts +++ b/server/typescript/packages/codegen-ts/test/agent-docs-surface.test.ts @@ -389,9 +389,11 @@ describe("agent/schema.md", () => { expect(page).not.toContain("ALTER TABLE"); }); - test("emits NO schema page when no schema is supplied", async () => { + test("emits the model-only schema page when no schema is supplied", async () => { const files = await emit(await load(MODEL)); - expect(files.has("agent/schema.md")).toBe(false); + const page = files.get("agent/schema.md") ?? ""; + // Built from the docs view, as every port writes it: no SQL type, no physical facts. + expect(page).toContain("The tables, columns and keys this model declares."); // The other two still emit — a missing dialect must not take the whole surface down. expect(files.has("agent/ui.md")).toBe(true); expect(files.has("agent/requirements.md")).toBe(true); diff --git a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts index 57e51f4af8..b47ea121f8 100644 --- a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts @@ -1551,8 +1551,8 @@ describe("ADR-0034 Amendments 8 and 9 — the requirements and agent-docs refere const a = await run(root, builtinRequirements()); const b = await run(root, refRequirements()); expect(b).toEqual(a); - // A ledger writes both forms; no ledger writes none — and the copy keeps that. - expect(paths(a)).toEqual(corpus.ledger ? ["requirements.md", "requirements.toon"] : []); + // A ledger writes the TOON; no ledger writes none — and the copy keeps that. + expect(paths(a)).toEqual(corpus.ledger ? ["requirements.toon"] : []); // The options an owned copy keeps: a directory and a target. expect(await run(root, refRequirements({ outDir: "ledger/" }))).toEqual( await run(root, builtinRequirements({ outDir: "ledger/" })), diff --git a/server/typescript/packages/codegen-ts/test/requirements-file-generator.test.ts b/server/typescript/packages/codegen-ts/test/requirements-file-generator.test.ts index 2217772c83..cf8f250a88 100644 --- a/server/typescript/packages/codegen-ts/test/requirements-file-generator.test.ts +++ b/server/typescript/packages/codegen-ts/test/requirements-file-generator.test.ts @@ -94,19 +94,10 @@ async function ctxFor(model: unknown): Promise { } describe("requirementsFile()", () => { - test("emits BOTH artifacts for a project with a ledger", async () => { + // The human requirements.md page is retired (1.3.0): people read the ledger in the explorer. + test("emits requirements.toon, and only that, for a project with a ledger", async () => { const files = await requirementsFile().generate(await ctxFor(WITH_LEDGER)); - expect(files.map((f) => f.path).sort()).toEqual([ - "requirements.md", - "requirements.toon", - ]); - }); - - test("the markdown carries the ledger's nesting", async () => { - const files = await requirementsFile().generate(await ctxFor(WITH_LEDGER)); - const md = files.find((f) => f.path === "requirements.md")?.content ?? ""; - expect(md).toContain("## checkout"); - expect(md).toContain("### checkout.capture"); + expect(files.map((f) => f.path)).toEqual(["requirements.toon"]); }); test("the TOON declares the row count", async () => { @@ -124,9 +115,6 @@ describe("requirementsFile()", () => { test("honours an outDir prefix without changing the filenames", async () => { const files = await requirementsFile({ outDir: "ledger" }).generate(await ctxFor(WITH_LEDGER)); - expect(files.map((f) => f.path).sort()).toEqual([ - "ledger/requirements.md", - "ledger/requirements.toon", - ]); + expect(files.map((f) => f.path)).toEqual(["ledger/requirements.toon"]); }); }); From 5cf0d74534d032f7e395d6f460bc5c959035ccef Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 07:06:46 -0500 Subject: [PATCH 07/21] wip: C# docs view storage, requirements and agent-docs from the view --- docs/ports/csharp.md | 10 + .../GenListAndSelectionTests.cs | 4 +- .../DocsPageConformanceTests.cs | 101 +++ .../DocsSiteGeneratorTests.cs | 8 +- .../GeneratorRegistryTests.cs | 3 + .../NoMagicPhysicalNamesTests.cs | 5 +- .../ReportingInertTests.cs | 12 +- .../MetaObjects.Codegen/Docs/DocsViewPages.cs | 598 ++++++++++++++++++ .../MetaObjects.Codegen/GeneratorRegistry.cs | 26 + .../Generators/AgentDocsGenerator.cs | 48 ++ .../Generators/RequirementsGenerator.cs | 40 ++ .../MetaObjects.Codegen.csproj | 5 + .../csharp/MetaObjects/DocsView/DocsView.cs | 8 +- .../MetaObjects/DocsView/DocsViewStorage.cs | 281 ++++++++ 14 files changed, 1137 insertions(+), 12 deletions(-) create mode 100644 server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs create mode 100644 server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs create mode 100644 server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs create mode 100644 server/csharp/MetaObjects.Codegen/Generators/RequirementsGenerator.cs create mode 100644 server/csharp/MetaObjects/DocsView/DocsViewStorage.cs diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 85ffaded4c..f2ae74b7ae 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -365,6 +365,16 @@ reference (`metamodel/INDEX.md`, `providers.md`, `types/.md`) from the s `templates/metamodel/` Mustache set; a `metamodel/.mustache` under its `TemplateRoot` overrides a shipped page. +**The agent pages.** The `requirements` generator writes `requirements.toon`, and `agent-docs` +writes `agent/requirements.md` and the model-only `agent/schema.md` (tables, columns, keys, +views, relationships and enums, named by this port's naming helpers). Both build their data from +the docs view (`MetaObjects.DocsView`, its `storage` section for the schema) and render the +shared `templates/requirements/` and `templates/agent/` Mustache pages, byte for byte what +`fixtures/docs-page-conformance/` pins (`DocsPageConformanceTests`). A `/.mustache` +under `TemplateRoot` overrides a shipped page. `agent/ui.md` and the physical schema (SQL types, +defaults, indexes) stay TypeScript's. The always-on agent file comes from the Node CLI +(`npx meta agent-docs`), which names these pages once a `gen` has written them. + **Generators write through a code writer.** `MetaObjects.Codegen.Writer.CsWriter` is where a generator's layout lives (ADR-0063): it owns the indent, the braces, the `using` lines and the blank lines, so a generator states what the file says and not how many spaces it takes. Every diff --git a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs index e6a4389706..1a1f29c73e 100644 --- a/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/GenListAndSelectionTests.cs @@ -47,7 +47,7 @@ public void ListHeader_says_generators_are_owned_via_eject() public void ListLines_prints_all_generators_with_stable_names_and_descriptions() { var lines = GenCommand.ListLines(_tmp); - Assert.Equal(20, lines.Count); + Assert.Equal(22, lines.Count); foreach (var name in new[] { "entity", "db-context", "routes", "output-parser", "extractor", @@ -66,6 +66,8 @@ public void ListLines_prints_all_generators_with_stable_names_and_descriptions() // ADR-0025 — the api reference, an ordinary entry since ADR-0034 Amendment 9. "api-docs", "metamodel-docs", + "requirements", + "agent-docs", // The model explorer, written with no Node. "docs-site", // The @expr indexes the EF model cannot carry, as SQL. diff --git a/server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs new file mode 100644 index 0000000000..a1f0fddf55 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs @@ -0,0 +1,101 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using MetaObjects.Codegen.Docs; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +/// +/// fixtures/docs-page-conformance/ — the requirement pages and the model-only schema page, one case +/// at a time. In order: the rows each builder reads off the docs view (rows/), the page data (data/), +/// then the bytes the requirements and agent-docs generators write; and the case expects +/// no file this port does not produce, nor the reverse. TypeScript is the source of the expected bytes. +/// +public sealed class DocsPageConformanceTests +{ + private static string Corpus => Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "docs-page-conformance", "cases"); + + public static IEnumerable Cases() => + Directory.GetDirectories(Corpus).OrderBy(d => d, StringComparer.Ordinal).Select(d => new object[] { Path.GetFileName(d) }); + + private static MetaRoot Load(string inputDir) + { + var sources = Directory.GetFiles(inputDir, "meta.*.json").OrderBy(f => f, StringComparer.Ordinal) + .Select(f => (IMetaDataSource)new InMemoryStringSource(File.ReadAllText(f), id: Path.GetFileName(f))).ToList(); + var load = new MetaDataLoader().Load(sources); + Assert.Empty(load.Errors.Select(e => e.Code + ": " + e.Message)); + return load.Root; + } + + /// The case chose a meta migrate dialect: its config sets migrate.dialect. + private static string? Dialect(string inputDir) + { + var path = Path.Combine(inputDir, ".metaobjects", "config.json"); + if (!File.Exists(path)) return null; + using var doc = JsonDocument.Parse(File.ReadAllText(path)); + return doc.RootElement.TryGetProperty("migrate", out var m) && m.TryGetProperty("dialect", out var d) ? d.GetString() : null; + } + + private static JsonNode? Json(object? data) => JsonSerializer.SerializeToNode(data); + + private static void AssertJson(string file, JsonNode? expected, JsonNode? actual) => + Assert.True(JsonNode.DeepEquals(expected, actual), $"{file} differs.\nexpected: {expected?.ToJsonString()}\nactual: {actual?.ToJsonString()}"); + + private static Dictionary ExpectedFiles(string dir, Func pick) => + Directory.Exists(dir) + ? Directory.GetFiles(dir, "*", SearchOption.AllDirectories) + .Select(f => Path.GetRelativePath(dir, f).Replace('\\', '/')).Where(pick) + .ToDictionary(f => f, f => File.ReadAllText(Path.Combine(dir, f)), StringComparer.Ordinal) + : []; + + [Fact] + public void The_corpus_is_not_empty() => Assert.NotEmpty(Cases()); + + [Theory] + [MemberData(nameof(Cases))] + public void Case_rows_data_and_bytes_equal_the_expected_files(string name) + { + string caseDir = Path.Combine(Corpus, name); + string input = Path.Combine(caseDir, "input"); + string expectedDir = Path.Combine(caseDir, "expected"); + var root = Load(input); + string? dialect = Dialect(input); + var view = DocsView.Build(root); + + // 1. The rows. + var rows = DocsViewPages.RequirementRows(view); + var expectedRows = ExpectedFiles(expectedDir, f => f.StartsWith("rows/", StringComparison.Ordinal)); + Assert.Equal(rows.Count > 0, expectedRows.ContainsKey("rows/requirements.json")); + if (rows.Count > 0) + AssertJson("rows/requirements.json", JsonNode.Parse(expectedRows["rows/requirements.json"]), Json(rows.Select(r => r.ToData()).ToList())); + var schemaRows = DocsViewPages.SchemaRows(view); + bool hasSchema = DocsViewPages.AgentSchemaData(view, dialect is not null) is not null; + Assert.Equal(hasSchema, expectedRows.ContainsKey("rows/schema.json")); + if (hasSchema) AssertJson("rows/schema.json", JsonNode.Parse(expectedRows["rows/schema.json"]), Json(schemaRows)); + + // 2. The page data. + var expectedData = ExpectedFiles(expectedDir, f => f.StartsWith("data/", StringComparison.Ordinal)); + var data = DocsViewPages.PageData(view, dialect is not null).ToList(); + Assert.Equal(expectedData.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList(), + data.Select(d => "data/" + d.File).OrderBy(k => k, StringComparer.Ordinal).ToList()); + foreach (var (file, page) in data) + AssertJson("data/" + file, JsonNode.Parse(expectedData["data/" + file]), Json(page)); + + // 3. The bytes, through the generators. + var ctx = new GenContext + { + Entities = root.Objects(), + Root = root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme", Dialect = dialect }, + }; + var written = new RequirementsGenerator().Generate(ctx).Concat(new AgentDocsGenerator().Generate(ctx)) + .ToDictionary(f => f.Path, f => f.Content, StringComparer.Ordinal); + var expectedPages = ExpectedFiles(expectedDir, f => !f.StartsWith("rows/", StringComparison.Ordinal) && !f.StartsWith("data/", StringComparison.Ordinal)); + Assert.Equal(expectedPages.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList(), written.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList()); + foreach (var (path, content) in expectedPages) + Assert.True(content == written[path], $"bytes differ for {path}"); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/DocsSiteGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DocsSiteGeneratorTests.cs index ff42a522b5..adc6705c69 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DocsSiteGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DocsSiteGeneratorTests.cs @@ -182,10 +182,10 @@ public void The_model_script_matches_TypeScript() var view = (JsonObject)JsonNode.Parse(File.ReadAllText( Path.Combine(RepoRoot(), "fixtures", "explorer-conformance", "model-alone", "expected.json")))!; var m = ExplorerModelScript.Of("T \u2028", "f", new Dictionary { ["b"] = "2", ["a"] = "1" }, null, view); - Assert.Equal("8ae24964eac47e67", m.Stamp); - Assert.Equal(10014, m.Script.Length); - Assert.Equal("3ae42a3977b053c76481fd1d5e7ca83f5f84fc1902608dbaec21bfe2cdc3019e", + Assert.Equal("950cb20a9b1bc1ca", m.Stamp); + Assert.Equal(12216, m.Script.Length); + Assert.Equal("a6a2e3094c558ab1823ebb782fa3f22747b13c2912f4be673a1a5d23c584c2e1", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(m.Script))).ToLowerInvariant()); - Assert.Equal("window.MO_STAMP = \"8ae24964eac47e67\";\n", ExplorerModelScript.StampScript(m.Stamp)); + Assert.Equal("window.MO_STAMP = \"950cb20a9b1bc1ca\";\n", ExplorerModelScript.StampScript(m.Stamp)); } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs index f0e87c32f2..34b718a9ab 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorRegistryTests.cs @@ -38,6 +38,9 @@ public sealed class GeneratorRegistryTests "api-docs", // The metamodel reference — the shared Mustache set over this port's registry. "metamodel-docs", + // The shared requirements / agent Mustache pages over the docs view. + "requirements", + "agent-docs", ]; [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs index fa6e6ba675..0e823b47a9 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs @@ -398,10 +398,11 @@ private static readonly (string Literal, string ShouldUse, Reach Reach, string W /// render-helper needs a --template-root and template is a /// primitive with no default walk; neither can emit here. docs-site writes the model /// explorer's data, which shows each field's physical column as documentation: it is data the - /// page displays, not code that could reference a constant. + /// page displays, not code that could reference a constant. agent-docs is the same + /// case: its agent/schema.md names every table and column for an agent to read. /// private static readonly IReadOnlyList GeneratorNames = - [.. GeneratorRegistry.Entries.Keys.Where(n => n is not ("render-helper" or "template" or "shared-model" or "docs-site"))]; + [.. GeneratorRegistry.Entries.Keys.Where(n => n is not ("render-helper" or "template" or "shared-model" or "docs-site" or "agent-docs"))]; /// Run the generator suite over the fixture. private static IReadOnlyList Generate() diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs index da7a9a1cb5..70b660a737 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportingInertTests.cs @@ -132,6 +132,10 @@ private static readonly (string Generator, string File)[] ReportFiles = /// The index and the agent page, which gain lines for a served report and lose none. private static readonly string[] ApiDocsSharedPages = ["api/csharp/README.md", "api/csharp/AGENT-API.md"]; + private const string AgentDocsGeneratorName = "agent-docs"; + /// The model-only schema page, which gains the served report's view and loses no line. + private const string AgentSchemaPage = "agent/schema.md"; + // Every derived field is filterable: a count and a sum of a currency take the ordered band. private const string ExpectedAllowlist = """ @@ -283,7 +287,8 @@ private static void AssertSameExceptTheReportRow( Assert.Equal(ExpectedDbContextLines, AddedLines(content, actual[path])); continue; } - if (ApiDocsSharedPages.Contains(path) && selection.Contains(ApiDocsGeneratorName)) + if ((ApiDocsSharedPages.Contains(path) && selection.Contains(ApiDocsGeneratorName)) + || (path == AgentSchemaPage && selection.Contains(AgentDocsGeneratorName))) { var added = AddedLines(content, actual[path]); Assert.NotEmpty(added); @@ -374,11 +379,12 @@ public void A_report_reaches_no_tier_but_its_row_its_mapping_its_allowlist_and_i Assert.DoesNotContain(files.Keys, k => k.Contains(sourceless, StringComparison.Ordinal)); Assert.DoesNotContain(files.Values, c => c.Contains(sourceless, StringComparison.Ordinal)); } - // Outside those three, the DbContext and the api reference, no generated file mentions the report. + // Outside those three, the DbContext, the api reference and the schema page (its view), no + // generated file mentions the report. var mentions = files.Where(f => f.Value.Contains("StoreTotals", StringComparison.Ordinal)) .Select(f => f.Key).OrderBy(k => k, StringComparer.Ordinal).ToList(); Assert.Equal( - ((string[])[DbContextFile, RowFile, AllowlistFile, RoutesFile, ExportModuleFile, ApiDocsReportPage, .. ApiDocsSharedPages]) + ((string[])[DbContextFile, RowFile, AllowlistFile, RoutesFile, ExportModuleFile, ApiDocsReportPage, AgentSchemaPage, .. ApiDocsSharedPages]) .OrderBy(k => k, StringComparer.Ordinal).ToList(), mentions); } diff --git a/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs b/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs new file mode 100644 index 0000000000..fa63fb7a8e --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs @@ -0,0 +1,598 @@ +// The agent pages, built from the docs view (docs/features/docs-view.md). +// +// `requirements.toon`, `agent/requirements.md` and the model-only `agent/schema.md` are shared +// Mustache templates (templates/requirements/, templates/agent/) every port renders. The view is +// the one input every port builds the same bytes of, so the rows each page starts from are read +// off the view and nothing else: the requirement rows from `requirements`, the node index from +// each requirement's resolved `implementedBy`, and the schema from `storage` plus the members of +// the nodes it links. This file is the C# port of TypeScript's docs-view-pages.ts, +// requirements-toon.ts, requirements-markdown.ts and agent-requirements-page.ts; the cross-port +// corpus is fixtures/docs-page-conformance/. +// +// The builders return plain dictionaries and lists: that is the payload the render engine takes, +// and what the corpus pins as JSON. + +using System.Text; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using MetaObjects.Render; + +namespace MetaObjects.Codegen.Docs; + +/// One requirement of the ledger, as the pages read it (expected/rows/requirements.json). +public sealed record RequirementRow( + string Path, int Depth, string? Title, string SubType, long? Level, string? Status, string? Disposition, + IReadOnlyList TrackedBy, string? Statement, string? Counterexample, string? Description, + IReadOnlyList ImplementedBy, IReadOnlyList ClaimedConcerns) +{ + /// The row as the corpus pins it: an absent optional value is an absent key. + public Dictionary ToData() + { + var d = new Dictionary { ["path"] = Path, ["depth"] = Depth }; + if (Title is not null) d["title"] = Title; + d["subType"] = SubType; + if (Level is not null) d["level"] = Level; + if (Status is not null) d["status"] = Status; + if (Disposition is not null) d["disposition"] = Disposition; + d["trackedBy"] = TrackedBy.Cast().ToList(); + if (Statement is not null) d["statement"] = Statement; + if (Counterexample is not null) d["counterexample"] = Counterexample; + if (Description is not null) d["description"] = Description; + d["implementedBy"] = ImplementedBy.Cast().ToList(); + d["claimedConcerns"] = ClaimedConcerns.Cast().ToList(); + return d; + } +} + +/// One page the docs-view builders make: where it is written, its template and its data. +public sealed record DocViewPage(string Path, string Group, string Template, Dictionary Data); + +public static class DocsViewPages +{ + /// The marker on the first line of every agent page. The same bytes in every port: the + /// page data is pinned by the corpus. + public const string AgentPageMarker = ""; + + public const string RequirementsToonPath = "requirements.toon"; + public const string AgentRequirementsPath = "agent/requirements.md"; + public const string AgentSchemaPath = "agent/schema.md"; + + private const string ToonTemplate = "requirements.toon"; + private const string LedgerTemplate = "requirements.md"; + private const string AgentRequirementsTemplate = "requirements.md"; + private const string AgentSchemaTemplate = "schema.md"; + + // ---- JSON helpers ----------------------------------------------------------------- + + private static string Str(JsonNode? n) => n is JsonValue v && v.TryGetValue(out var s) ? s : ""; + + private static string? Opt(JsonNode? n) => Str(n) is { Length: > 0 } s ? s : null; + + private static JsonArray Arr(JsonNode? n) => n as JsonArray ?? []; + + private static JsonObject Obj(JsonNode? n) => n as JsonObject ?? []; + + private static bool Bool(JsonNode? n) => n is JsonValue v && v.TryGetValue(out var b) && b; + + private static long? Num(JsonNode? n) + { + if (n is not JsonValue v) return null; + if (v.TryGetValue(out var l)) return l; + if (v.TryGetValue(out var d)) return (long)d; + return null; + } + + private static IEnumerable Objs(JsonNode? n) => Arr(n).OfType(); + + // ---- requirements ----------------------------------------------------------------- + + /// The requirement rows of the view, in document order. is the + /// collection's ledger predicate over a requirement's qualified address: a dependency's + /// requirement the project did not inherit is left out. + public static List RequirementRows(JsonObject view, Func? inLedger = null) => + Objs(view["requirements"]) + .Where(r => inLedger is null || inLedger(Qualified(r))) + .Select(r => + { + var claims = Objs(r["implementedBy"]).ToList(); + return new RequirementRow( + Str(r["address"]), (int)(Num(r["depth"]) ?? 0), Opt(r["title"]), Str(r["subType"]), Num(r["level"]), + Opt(r["status"]), Opt(r["disposition"]), + Arr(r["trackedBy"]).Select(Str).ToList(), + Opt(r["statement"]), Opt(r["counterexample"]), Opt(r["description"]), + claims.Select(l => Str(l["ref"])).ToList(), + claims.Where(l => Bool(l["resolves"])).Select(l => Str(Obj(l["target"])["kind"])).Distinct(StringComparer.Ordinal).ToList()); + }).ToList(); + + private static string Qualified(JsonObject requirement) + { + string package = Str(requirement["package"]); + string address = Str(requirement["address"]); + return package.Length == 0 ? address : package + "::" + address; + } + + private sealed record NodeClaim(string Path, string SubType, long? Level, string? Status, string? Statement); + + private sealed record NodeEntry(string Address, string Concern, List Claims); + + /// Claimed node to the requirements that claim it, sorted by the node's id. A claim that + /// does not resolve is left out, as verify is what reports it. + private static List NodeIndex(JsonObject view, Func? inLedger) + { + var by = new Dictionary(StringComparer.Ordinal); + foreach (var r in Objs(view["requirements"])) + { + if (inLedger is not null && !inLedger(Qualified(r))) continue; + foreach (var link in Objs(r["implementedBy"])) + { + if (!Bool(link["resolves"])) continue; + var target = Obj(link["target"]); + string id = Str(target["id"]); + if (!by.TryGetValue(id, out var entry)) by[id] = entry = new NodeEntry(id, Str(target["kind"]), []); + entry.Claims.Add(new NodeClaim(Str(r["address"]), Str(r["subType"]), Num(r["level"]), Opt(r["status"]), Opt(r["statement"]))); + } + } + return by.Values.OrderBy(e => e.Address, StringComparer.Ordinal).ToList(); + } + + // ---- requirements.md (the ledger) --------------------------------------------------- + + /// One extra # on every line that starts a heading, capped at h6. + private static string Demote(string text) => + Regex.Replace(text, "^(#{1,6}) ", m => new string('#', Math.Min(m.Groups[1].Length + 1, 6)) + " ", RegexOptions.Multiline); + + private static string Heading(int depth) => new('#', Math.Min(depth + 2, 6)); + + private static string Collapse(string text) => Regex.Replace(text, @"\s+", " ").Trim(); + + private static string Normalize(string s) => Regex.Replace(s.ToLowerInvariant(), "[^a-z0-9]", ""); + + private static bool TitleRestatesLeaf(string path, string title) => + Normalize(path[(path.LastIndexOf('.') + 1)..]) == Normalize(title); + + private static string HeadingLine(RequirementRow r) + { + string? title = r.Title is null ? null : Collapse(r.Title); + string label = title is null || title.Length == 0 || TitleRestatesLeaf(r.Path, title) ? "" : $" — {title}"; + return $"{Heading(r.Depth)} {r.Path}{label}"; + } + + private static string Facts(RequirementRow r) + { + var parts = new List { $"`{r.SubType}`" }; + if (r.Level is { } level) parts.Add($"**L{level}**"); + if (r.Status is not null) parts.Add($"status: `{r.Status}`"); + if (r.Disposition is not null) parts.Add($"disposition: `{r.Disposition}`"); + if (r.TrackedBy.Count > 0) parts.Add($"tracked: {string.Join(", ", r.TrackedBy)}"); + return string.Join(" · ", parts); + } + + /// What requirements/requirements.md.mustache renders. is the + /// ledger as a section of a larger page: no Requirements title, every heading one level down. + public static Dictionary LedgerData(IReadOnlyList rows, bool embedded) + { + string Line(string text) => embedded ? Demote(text) : text; + return new() + { + ["embedded"] = embedded, + ["count"] = rows.Count, + ["plural"] = rows.Count == 1 ? "" : "s", + ["entries"] = rows.Select(r => + { + var e = new Dictionary { ["heading"] = Line(HeadingLine(r)), ["facts"] = Line(Facts(r)) }; + if (r.Statement is not null) e["statement"] = Line(r.Statement); + if (r.Counterexample is not null) e["counterexample"] = Line($"**Counterexample:** {r.Counterexample}"); + if (r.Description is not null) e["description"] = Line(r.Description); + if (r.ImplementedBy.Count > 0) + e["implementedBy"] = Line($"**Implemented by:** {string.Join(", ", r.ImplementedBy.Select(c => $"`{c}`"))}"); + return (object?)e; + }).ToList(), + }; + } + + // ---- requirements.toon -------------------------------------------------------------- + + private static readonly string[] ToonFields = ["path", "subType", "level", "status", "disposition", "claims", "statement"]; + + private static readonly Regex NumericLike = new(@"^-?[0-9]+(\.[0-9]+)?(e[+-]?[0-9]+)?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + private static readonly Regex LeadingZero = new("^0[0-9]+$"); + private static readonly Regex ToonUnsafe = new(@"[:""\\\[\]{},\x00-\x1f]"); + + /// One cell as TOON writes it in a comma-delimited row: a number bare, a string bare when + /// safe and quoted (with TOON's escapes) when it is empty, padded, numeric- or literal-looking, or + /// carries a delimiter, a colon, a quote, a bracket, a leading - or a control character. + public static string ToonCell(string value) + { + bool safe = value.Length > 0 && value == value.Trim() + && value is not ("true" or "false" or "null") + && !NumericLike.IsMatch(value) && !LeadingZero.IsMatch(value) + && !ToonUnsafe.IsMatch(value) && !value.StartsWith('-'); + if (safe) return value; + var sb = new StringBuilder("\""); + foreach (char ch in value) + { + switch (ch) + { + case '\\': sb.Append("\\\\"); break; + case '"': sb.Append("\\\""); break; + case '\n': sb.Append("\\n"); break; + case '\r': sb.Append("\\r"); break; + case '\t': sb.Append("\\t"); break; + case < ' ': sb.Append("\\u").Append(((int)ch).ToString("x4")); break; + default: sb.Append(ch); break; + } + } + return sb.Append('"').ToString(); + } + + /// What requirements/requirements.toon.mustache renders: every cell a finished literal. + public static Dictionary ToonData(IReadOnlyList rows) => new() + { + ["count"] = rows.Count, + ["fields"] = "{" + string.Join(",", ToonFields) + "}", + ["rows"] = rows.Select(r => (object?)new Dictionary + { + ["line"] = string.Join(",", new[] + { + ToonCell(r.Path), + ToonCell(r.SubType), + r.Level is { } l ? l.ToString() : ToonCell(""), + ToonCell(r.Status ?? ""), + ToonCell(r.Disposition ?? ""), + ToonCell(string.Join(" ", r.ImplementedBy)), + ToonCell(r.Statement ?? ""), + }), + }).ToList(), + }; + + // ---- agent/requirements.md ---------------------------------------------------------- + + private static string MdCell(string text) => text.Replace("|", "\\|"); + + /// What agent/requirements.md.mustache renders. is the ledger + /// page's own template rendered in its embedded form, trailing line breaks removed. Null for a + /// model declaring no requirements, which gets no page. + public static Dictionary? AgentRequirementsData( + JsonObject view, string ledger, Func? inLedger = null) + { + var rows = RequirementRows(view, inLedger); + if (rows.Count == 0) return null; + var index = NodeIndex(view, inLedger); + var stated = new Dictionary(StringComparer.Ordinal); + foreach (var entry in index) + foreach (var c in entry.Claims) + if (c.Statement is not null) stated[c.Path] = (c.SubType, c.Statement); + var statements = stated.OrderBy(kv => kv.Key, StringComparer.Ordinal) + .Select(kv => (object?)new Dictionary + { + ["path"] = kv.Key, ["subType"] = kv.Value.SubType, ["statement"] = MdCell(Collapse(kv.Value.Statement)), + }).ToList(); + return new() + { + ["generatedMarker"] = AgentPageMarker, + ["hasNodeIndex"] = index.Count > 0, + ["nodeIndex"] = index.Select(e => (object?)new Dictionary + { + ["address"] = e.Address, + ["concern"] = e.Concern, + ["claims"] = string.Join("
    ", e.Claims.Select(c => + $"`{c.Path}`{(c.Level is { } l ? $" L{l}" : "")}{(c.Status is not null ? $" ({c.Status})" : "")}")), + }).ToList(), + ["hasStatements"] = statements.Count > 0, + ["statements"] = statements, + ["ledger"] = ledger.TrimEnd('\n'), + }; + } + + // ---- agent/schema.md ---------------------------------------------------------------- + + private static string StorageKey(string name, string schema) => schema.Length == 0 ? name : $"{schema}.{name}"; + + /// The model-only rows layer of the schema page, read off the view's storage + /// (expected/rows/schema.json). + public static Dictionary SchemaRows(JsonObject view) + { + var storage = Obj(view["storage"]); + var declared = new List<(string Key, string Id)>(); + var tables = Objs(storage["tables"]).Select(t => + { + declared.Add((StorageKey(Str(t["name"]), Str(t["schema"])), Str(Obj(t["declaredBy"])["id"]))); + var row = new Dictionary { ["name"] = Str(t["name"]) }; + if (Opt(t["schema"]) is { } schema) row["schema"] = schema; + if (Opt(t["description"]) is { } description) row["description"] = description; + row["primaryKey"] = Arr(t["primaryKey"]).Select(n => (object?)Str(n)).ToList(); + row["columns"] = Objs(t["columns"]).Select(c => + { + var col = new Dictionary { ["name"] = Str(c["name"]), ["nullable"] = Bool(c["nullable"]) }; + if (Opt(c["identity"]) is { } identity) col["identity"] = identity; + if (Opt(c["description"]) is { } d) col["description"] = d; + return (object?)col; + }).ToList(); + row["foreignKeys"] = Objs(t["foreignKeys"]).Select(f => (object?)new Dictionary + { + ["columns"] = Arr(f["columns"]).Select(n => (object?)Str(n)).ToList(), + ["refTable"] = Str(f["refTable"]), + ["refColumns"] = Arr(f["refColumns"]).Select(n => (object?)Str(n)).ToList(), + }).ToList(); + return (object?)row; + }).ToList(); + var views = Objs(storage["views"]).Select(v => + { + declared.Add((StorageKey(Str(v["name"]), Str(v["schema"])), Str(Obj(v["declaredBy"])["id"]))); + var row = new Dictionary { ["name"] = Str(v["name"]) }; + if (Opt(v["schema"]) is { } schema) row["schema"] = schema; + return (object?)row; + }).ToList(); + var declaredBy = new Dictionary(); + foreach (var (key, id) in declared.OrderBy(d => d.Key, StringComparer.Ordinal)) declaredBy[key] = id; + return new() { ["tables"] = tables, ["views"] = views, ["declaredBy"] = declaredBy }; + } + + private static Dictionary MembersById(JsonObject view) + { + var map = new Dictionary(StringComparer.Ordinal); + void Visit(JsonObject m) + { + map[Str(m["id"])] = m; + foreach (var g in Objs(m["memberGroups"])) foreach (var c in Objs(g["members"])) Visit(c); + } + foreach (var n in Objs(view["nodes"])) + foreach (var g in Objs(n["memberGroups"])) foreach (var m in Objs(g["members"])) Visit(m); + return map; + } + + private static List DirectMembers(JsonObject owner, string type) => + Objs(owner["memberGroups"]).FirstOrDefault(g => Str(g["type"]) == type) is { } g ? Objs(g["members"]).ToList() : []; + + private static JsonObject? Attr(JsonObject owner, string name) => Objs(owner["attrs"]).FirstOrDefault(a => Str(a["name"]) == name); + + private static JsonNode? AttrValue(JsonObject owner, string name) => Attr(owner, name)?["value"]; + + /// A string attribute as a page prints it: a resolved reference by its link's label, + /// anything else as its text. + private static string? AttrText(JsonObject owner, string name) + { + if (Attr(owner, name) is not { } a || a["value"] is not JsonValue v || !v.TryGetValue(out var value)) return null; + var link = Arr(a["values"]).FirstOrDefault() is JsonObject first ? first["link"] as JsonObject : null; + string text = link is not null && !Bool(link["unresolved"]) ? Str(link["label"]) : value; + return text.Length == 0 ? null : text; + } + + private static string Cols(IEnumerable names) + { + var list = names.ToList(); + return list.Count == 0 ? "—" : string.Join(", ", list.Select(c => $"`{c}`")); + } + + private static string KeyCell(JsonObject table, string column) + { + var pk = Arr(table["primaryKey"]).Select(Str).ToList(); + var roles = new List(); + if (pk.Contains(column)) roles.Add(pk.Count > 1 ? "PK (composite)" : "PK"); + var fk = Objs(table["foreignKeys"]).FirstOrDefault(f => Arr(f["columns"]).Select(Str).Contains(column)); + if (fk is not null) roles.Add($"FK → `{Str(fk["refTable"])}`"); + return string.Join(" · ", roles); + } + + private static string? LineageOf(JsonObject? field) + { + var origin = field is null ? null : DirectMembers(field, "origin").FirstOrDefault(); + if (origin is null) return null; + string? T(string name) => AttrText(origin, name); + string Via() => T("via") is { } via ? $" via `{via}`" : ""; + switch (Str(origin["subType"])) + { + case "passthrough": return $"passthrough from `{T("from") ?? "?"}`" + Via(); + case "aggregate": return $"`{T("agg") ?? "?"}`" + (T("of") is { } of ? $" of `{of}`" : "") + Via(); + case "first": + return "first" + (T("of") is { } o ? $" `{o}`" : "") + Via() + (T("orderBy") is { } ob ? $" ordered by `{ob}`" : ""); + case "computed": return "computed from a declared `@expr`"; + default: return $"`origin.{Str(origin["subType"])}`"; + } + } + + private static string CardinalityPhrase(string? cardinality, string? through) => cardinality switch + { + "many" => through is not null ? "many-to-many" : "one-to-many", + "one" => "many-to-one", + _ => "cardinality not declared", + }; + + private static string JsText(JsonNode? n) => + n is JsonValue v && v.TryGetValue(out var s) ? s : n?.ToJsonString() ?? "undefined"; + + /// The data agent/schema.md.mustache renders for the model-only page, built from the + /// view alone. : the project chose a meta migrate dialect + /// (migrate.dialect in .metaobjects/config.json). Null when the model declares no table + /// and no view: no page. + public static Dictionary? AgentSchemaData(JsonObject view, bool hasMigrate, Func? inScope = null) + { + var storage = Obj(view["storage"]); + // A dependency's node the project did not take into scope is not the project's schema. + bool Scoped(string id) => inScope is null || inScope(id); + var tables = Objs(storage["tables"]).Where(t => Scoped(Str(Obj(t["declaredBy"])["id"]))).ToList(); + var views = Objs(storage["views"]).Where(v => Scoped(Str(Obj(v["declaredBy"])["id"]))).ToList(); + if (tables.Count == 0 && views.Count == 0) return null; + var members = MembersById(view); + string FieldName(string id) => members.TryGetValue(id, out var m) ? Str(m["name"]) : ""; + + var tableData = tables.Select(t => + { + var columns = Objs(t["columns"]).ToList(); + var described = columns.Where(c => Str(c["description"]).Length > 0).ToList(); + var fks = Objs(t["foreignKeys"]).Select(f => + $"{Cols(Arr(f["columns"]).Select(Str))} → `{Str(f["refTable"])}`({Cols(Arr(f["refColumns"]).Select(Str))})").ToList(); + var d = new Dictionary + { + ["heading"] = $"`{StorageKey(Str(t["name"]), Str(t["schema"]))}`", + ["tableDeclaredBy"] = Str(Obj(t["declaredBy"])["id"]), + }; + if (Str(t["description"]).Length > 0) d["tableDescription"] = Collapse(Str(t["description"])); + d["columns"] = columns.Select(c => + { + var field = c["field"] as JsonObject; + return (object?)new Dictionary + { + ["name"] = Str(c["name"]), + ["fieldCell"] = field is null ? "" : $"`{FieldName(Str(field["id"]))}`", + ["declaredCell"] = field is null ? "" : $"`{Str(field["kind"])}`", + ["sqlTypeCell"] = "", + ["nullCell"] = Bool(c["nullable"]) ? "yes" : "no", + ["defaultCell"] = "", + ["keyCell"] = KeyCell(t, Str(c["name"])), + }; + }).ToList(); + d["hasDescribed"] = described.Count > 0; + d["described"] = described.Select(c => (object?)new Dictionary + { ["name"] = Str(c["name"]), ["text"] = Collapse(Str(c["description"])) }).ToList(); + d["hasIndexes"] = false; + d["indexes"] = new List(); + d["hasForeignKeys"] = fks.Count > 0; + d["foreignKeys"] = fks.Cast().ToList(); + d["hasChecks"] = false; + d["checks"] = new List(); + return (object?)d; + }).ToList(); + + var viewData = views.Select(v => + { + var lineage = Objs(v["columns"]).SelectMany(c => + { + string? text = LineageOf(c["field"] is JsonObject f && members.TryGetValue(Str(f["id"]), out var m) ? m : null); + return text is null ? [] : new[] { (object?)new Dictionary { ["column"] = Str(c["name"]), ["text"] = text } }; + }).ToList(); + return (object?)new Dictionary + { + ["heading"] = $"`{StorageKey(Str(v["name"]), Str(v["schema"]))}`", + ["viewDeclaredBy"] = Str(Obj(v["declaredBy"])["id"]), + ["hasLineage"] = lineage.Count > 0, + ["lineage"] = lineage, + }; + }).ToList(); + + // Every relationship as written, in declaration order of its object. + var byOrder = Objs(view["nodes"]).OrderBy(n => Num(n["order"]) ?? 0).ToList(); + var relationships = new List(); + foreach (var n in byOrder) + { + if (Str(n["type"]) != "object" || !Scoped(Str(n["id"]))) continue; + foreach (var rel in DirectMembers(n, "relationship")) + { + string? through = AttrText(rel, "through"); + string? onDelete = AttrText(rel, "onDelete"); + var parts = new List + { + $"`{Str(n["id"])}.{Str(rel["name"])}`", + $"`{Str(rel["subType"])}`", + $"{CardinalityPhrase(AttrValue(rel, "cardinality") is JsonValue c && c.TryGetValue(out var cs) ? cs : null, through)} → `{AttrText(rel, "objectRef") ?? "?"}`", + }; + if (through is not null) parts.Add($"through `{through}`"); + if (onDelete is not null) parts.Add($"on delete `{onDelete}`"); + relationships.Add(string.Join(" · ", parts)); + } + } + + // Every enum field of a table-backed object, in declaration order of its object. + var tableBacked = new HashSet(tables.SelectMany(t => Objs(t["objects"]).Select(o => Str(o["id"]))), StringComparer.Ordinal); + var enums = new List(); + foreach (var n in byOrder) + { + if (!tableBacked.Contains(Str(n["id"]))) continue; + foreach (var f in DirectMembers(n, "field")) + { + if (Str(f["subType"]) != "enum") continue; + var list = AttrValue(f, "values") is JsonArray values ? values.Select(JsText).ToList() : []; + if (list.Count == 0) continue; + string storageKind = AttrValue(f, "intValueMap") is JsonObject map + ? $"int-backed ({string.Join(", ", list.Select(m => $"{m}={(map.TryGetPropertyValue(m, out var v) ? JsText(v) : "undefined")}"))})" + : "string-backed"; + enums.Add(new Dictionary + { + ["field"] = $"{Str(n["id"])}.{Str(f["name"])}", + ["members"] = string.Join(", ", list.Select(m => $"`{m}`")), + ["storage"] = storageKind, + }); + } + } + + bool anyDescription = tables.Any(t => Str(t["description"]).Length > 0 || Objs(t["columns"]).Any(c => Str(c["description"]).Length > 0)); + return new() + { + ["generatedMarker"] = AgentPageMarker, + ["physical"] = false, + ["dialect"] = "", + ["hasMigrate"] = hasMigrate, + ["descriptionNudge"] = !anyDescription && tables.Count > 0, + ["hasTables"] = tableData.Count > 0, + ["tables"] = tableData, + ["hasViews"] = viewData.Count > 0, + ["hasReportView"] = views.Any(v => Objs(v["objects"]).Any(o => Str(o["kind"]) == "object.report")), + ["views"] = viewData, + ["hasRelationships"] = relationships.Count > 0, + ["relationships"] = relationships, + ["hasEnums"] = enums.Count > 0, + ["enums"] = enums, + }; + } + + // ---- templates and rendering --------------------------------------------------------- + + private const string ResourcePrefix = "MetaObjects.Codegen.Templates."; + + /// The text of templates/<group>/<page>.mustache: the project's own copy + /// under when there is one, else the one shipped in the package. + public static string Template(string group, string page, string? templateRoot) + { + string file = page + ".mustache"; + if (templateRoot is { Length: > 0 } root && System.IO.Path.Combine(root, group, file) is var path && File.Exists(path)) + return File.ReadAllText(path); + using var stream = typeof(IGenerator).Assembly.GetManifestResourceStream($"{ResourcePrefix}{group}.{file}") + ?? throw new InvalidOperationException($"embedded template missing: {ResourcePrefix}{group}.{file}"); + using var reader = new StreamReader(stream); + return reader.ReadToEnd(); + } + + private static string RenderTemplate(string text, object data) => + Renderer.Render(new RenderRequest + { + Template = text, + Payload = data, + Provider = new InMemoryProvider(new Dictionary()), + Format = Escapers.FORMAT_TEXT, + }); + + /// Every page of the view, in the order they are written: requirements.toon, + /// agent/requirements.md and agent/schema.md. A page the model gives no content for + /// is not in the list. and pick the + /// requirements and the agent-docs generator's pages. + public static IEnumerable<(string Path, string Content)> Render( + JsonObject view, bool hasMigrate, string? templateRoot, Func? inLedger, + bool includeRequirements, bool includeAgent, Func? inScope = null) + { + var rows = RequirementRows(view, inLedger); + if (includeRequirements && rows.Count > 0) + yield return (RequirementsToonPath, RenderTemplate(Template("requirements", ToonTemplate, templateRoot), ToonData(rows))); + if (!includeAgent) yield break; + var data = rows.Count == 0 ? null : AgentRequirementsData( + view, RenderTemplate(Template("requirements", LedgerTemplate, templateRoot), LedgerData(rows, embedded: true)), inLedger); + if (data is not null) + yield return (AgentRequirementsPath, RenderTemplate(Template("agent", AgentRequirementsTemplate, templateRoot), data)); + if (AgentSchemaData(view, hasMigrate, inScope) is { } schema) + yield return (AgentSchemaPath, RenderTemplate(Template("agent", AgentSchemaTemplate, templateRoot), schema).TrimEnd('\n') + "\n"); + } + + /// The page data the corpus pins, by its file name under expected/data/. + public static IEnumerable<(string File, Dictionary Data)> PageData(JsonObject view, bool hasMigrate, Func? inLedger = null) + { + var rows = RequirementRows(view, inLedger); + if (rows.Count > 0) + { + yield return ("requirements.toon.json", ToonData(rows)); + yield return ("ledger.md.json", LedgerData(rows, embedded: true)); + } + var data = rows.Count == 0 ? null : AgentRequirementsData( + view, RenderTemplate(Template("requirements", LedgerTemplate, null), LedgerData(rows, embedded: true)), inLedger); + if (data is not null) yield return ("agent-requirements.md.json", data); + if (AgentSchemaData(view, hasMigrate) is { } schema) yield return ("agent-schema.md.json", schema); + } +} diff --git a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs index 79d331c560..fecac2f0bd 100644 --- a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs +++ b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs @@ -328,6 +328,32 @@ private static IGenerator RenderHelper(GeneratorBuildContext ctx) => Note = "Reads no model objects. A project's metamodel/.mustache under the template root overrides the shipped template.", SourceFileName = "MetamodelDocsGenerator.cs", }, + // The requirement ledger as requirements.toon: the shared templates/requirements/ Mustache page over the docs view. + ["requirements"] = new() + { + Name = "requirements", + Description = "The requirement ledger as requirements.toon, for tools; people read it in the explorer (docs-site).", + Tier = GeneratorTier.Neutral, + Layer = GeneratorLayer.Docs, + Factory = ctx => new RequirementsGenerator { TemplateRoot = ctx.TemplateRoot }, + Options = "OutDir, SubDir (default \"\"), TemplateRoot (init properties on the entry in codegen/Generators.cs)", + Note = "A model that declares no requirement.* node gets no file. A project's requirements/requirements.toon.mustache under the template root overrides the shipped template.", + SourceFileName = "RequirementsGenerator.cs", + Companions = ["Docs/DocsViewPages.cs"], + }, + // The pages for a coding agent: agent/requirements.md and the model-only agent/schema.md, over the docs view. + ["agent-docs"] = new() + { + Name = "agent-docs", + Description = "Pages written for a coding agent working in the project: the model-only schema and the requirements (agent/ui.md and the physical schema are TypeScript's).", + Tier = GeneratorTier.Neutral, + Layer = GeneratorLayer.Docs, + Factory = ctx => new AgentDocsGenerator { TemplateRoot = ctx.TemplateRoot }, + Options = "OutDir, SubDir (default \"\"), TemplateRoot (init properties on the entry in codegen/Generators.cs)", + Note = "A model with no requirement gets no requirements page, and one with no table and no view gets no schema page. A project's agent/.mustache under the template root overrides the shipped template.", + SourceFileName = "AgentDocsGenerator.cs", + Companions = ["Docs/DocsViewPages.cs"], + }, // The model explorer over the docs view (no Node). Exempt from eject (registry.json): the site // builder is engine; a project owns the explorer's theme and page templates under codegen/docs-site/. ["docs-site"] = new() diff --git a/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs new file mode 100644 index 0000000000..524bf6612a --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs @@ -0,0 +1,48 @@ +// agent-docs — the pages written for a coding agent working in the project: agent/requirements.md +// (the node index and the embedded ledger) and the model-only agent/schema.md (tables, columns, +// keys, views, relationships and enums, named by this port's own naming helpers). The shared +// templates/agent/ Mustache pages rendered over the docs view this port builds from the loaded model +// (MetaObjects.DocsView), the page data built by Docs/DocsViewPages.cs and held to the same bytes by +// fixtures/docs-page-conformance/. agent/ui.md and the physical schema (SQL types, defaults, indexes) +// stay TypeScript's. +// +// An ordinary entry in codegen/Generators.cs (ADR-0034 Amendment 9). A model with no requirement +// gets no requirements page; a model with no table and no view gets no schema page. A project's own +// `agent/.mustache` (and `requirements/requirements.md.mustache`, the ledger it embeds) under +// TemplateRoot wins over the shipped template. + +using MetaObjects.Codegen.Docs; +using MetaObjects.Meta; + +namespace MetaObjects.Codegen.Generators; + +public sealed class AgentDocsGenerator : IGenerator +{ + public string Name => "agent-docs"; + + /// The docs output root the pages are written under; null writes under the run's --out. + public string? OutDir { get; init; } + + /// Where under the pages land; "" writes them at its root. + public string SubDir { get; init; } = ""; + + /// A project template directory: agent/<page>.mustache there overrides the shipped one. + public string? TemplateRoot { get; init; } + + public bool WholeModel => true; + + public IEnumerable Generate(GenContext ctx) + { + var imports = ctx.Root.ImportScope; + var view = DocsView.Build(ctx.Root); + // The project chose `meta migrate` (migrate.dialect in .metaobjects/config.json). + bool hasMigrate = !string.IsNullOrEmpty(ctx.Config.Dialect); + // An object a dependency brought and the project did not take into scope is left out of the schema. + var inScope = ctx.Root.Objects().Where(ctx.Root.InScope).Select(o => o.ResolutionKey()).ToHashSet(StringComparer.Ordinal); + string prefix = SubDir.TrimEnd('/') is { Length: > 0 } sub ? sub + "/" : ""; + foreach (var (path, content) in DocsViewPages.Render( + view, hasMigrate, TemplateRoot, fqn => imports?.InLedger(fqn) ?? true, + includeRequirements: false, includeAgent: true, inScope.Contains)) + yield return new EmittedFile(prefix + path, content) { WholeModel = true }; + } +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/RequirementsGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RequirementsGenerator.cs new file mode 100644 index 0000000000..b81b4b8924 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Generators/RequirementsGenerator.cs @@ -0,0 +1,40 @@ +// requirements — the requirement ledger as requirements.toon, for tools; people read it in the +// explorer (docs-site). The shared templates/requirements/ Mustache page rendered over the docs view +// this port builds from the loaded model (MetaObjects.DocsView), the page data built by +// Docs/DocsViewPages.cs and held to the same bytes by fixtures/docs-page-conformance/. +// +// An ordinary entry in codegen/Generators.cs, run by `dotnet meta gen` (ADR-0034 Amendment 9). A +// model that declares no requirement.* node gets no file. A project's own +// `requirements/requirements.toon.mustache` under TemplateRoot wins over the shipped template. + +using MetaObjects.Codegen.Docs; +using MetaObjects.Meta; + +namespace MetaObjects.Codegen.Generators; + +public sealed class RequirementsGenerator : IGenerator +{ + public string Name => "requirements"; + + /// The docs output root the page is written under; null writes under the run's --out. + public string? OutDir { get; init; } + + /// Where under the page lands; "" writes it at its root. + public string SubDir { get; init; } = ""; + + /// A project template directory: requirements/requirements.toon.mustache there overrides the shipped one. + public string? TemplateRoot { get; init; } + + public bool WholeModel => true; + + public IEnumerable Generate(GenContext ctx) + { + var imports = ctx.Root.ImportScope; + var view = DocsView.Build(ctx.Root); + string prefix = SubDir.TrimEnd('/') is { Length: > 0 } sub ? sub + "/" : ""; + foreach (var (path, content) in DocsViewPages.Render( + view, hasMigrate: false, TemplateRoot, fqn => imports?.InLedger(fqn) ?? true, + includeRequirements: true, includeAgent: false)) + yield return new EmittedFile(prefix + path, content) { WholeModel = true }; + } +} diff --git a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj index 10664c0b39..5e10083319 100644 --- a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj +++ b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj @@ -55,6 +55,8 @@ + + @@ -64,6 +66,7 @@ + @@ -78,6 +81,8 @@ + + "; + + public static final String REQUIREMENTS_TOON_REF = "requirements/requirements.toon"; + public static final String REQUIREMENTS_LEDGER_REF = "requirements/requirements.md"; + public static final String AGENT_REQUIREMENTS_REF = "agent/requirements.md"; + public static final String AGENT_SCHEMA_REF = "agent/schema.md"; + + private static final String NO_VALUE = "—"; + private static final String TYPE_OBJECT = "object"; + private static final String TYPE_FIELD = "field"; + private static final String TYPE_ORIGIN = "origin"; + private static final String TYPE_RELATIONSHIP = "relationship"; + private static final String KIND_REPORT = "object.report"; + private static final String SUBTYPE_ENUM = "enum"; + + private DocsViewPages() { + } + + // ---- json reads -------------------------------------------------------------------- + + private static String str(JsonObject o, String key) { + JsonElement e = o.get(key); + return e == null || e.isJsonNull() || !e.isJsonPrimitive() ? "" : e.getAsString(); + } + + private static JsonArray arr(JsonObject o, String key) { + JsonElement e = o.get(key); + return e != null && e.isJsonArray() ? e.getAsJsonArray() : new JsonArray(); + } + + private static List objects(JsonArray a) { + List out = new ArrayList<>(); + for (JsonElement e : a) if (e.isJsonObject()) out.add(e.getAsJsonObject()); + return out; + } + + private static boolean has(JsonObject o, String key) { + JsonElement e = o.get(key); + return e != null && !e.isJsonNull(); + } + + private static String opt(String s) { + return s.isEmpty() ? null : s; + } + + // ---- requirements ------------------------------------------------------------------ + + /** One requirement row of the view, in document order, as the rows layer pins it. */ + public static List> requirementRows(JsonObject view, Predicate inLedger) { + List> rows = new ArrayList<>(); + for (JsonObject r : objects(arr(view, "requirements"))) { + if (inLedger != null && !inLedger.test(str(r, "qualifiedPath"))) continue; + Map row = new LinkedHashMap<>(); + row.put("path", str(r, "address")); + row.put("depth", r.get("depth").getAsInt()); + if (opt(str(r, "title")) != null) row.put("title", str(r, "title")); + row.put("subType", str(r, "subType")); + if (has(r, "level")) row.put("level", r.get("level").getAsInt()); + for (String k : new String[]{"status", "disposition"}) if (opt(str(r, k)) != null) row.put(k, str(r, k)); + List tracked = new ArrayList<>(); + for (JsonElement t : arr(r, "trackedBy")) tracked.add(t.getAsString()); + row.put("trackedBy", tracked); + for (String k : new String[]{"statement", "counterexample", "description"}) { + if (opt(str(r, k)) != null) row.put(k, str(r, k)); + } + List refs = new ArrayList<>(); + Set concerns = new LinkedHashSet<>(); + for (JsonObject l : objects(arr(r, "implementedBy"))) { + refs.add(str(l, "ref")); + if (l.get("resolves").getAsBoolean()) concerns.add(str(l.getAsJsonObject("target"), "kind")); + } + row.put("implementedBy", refs); + row.put("claimedConcerns", new ArrayList<>(concerns)); + rows.add(row); + } + return rows; + } + + @SuppressWarnings("unchecked") + private static List list(Object o) { + return (List) o; + } + + private static String heading(int depth) { + return "#".repeat(Math.min(depth + 2, 6)); + } + + private static String normalize(String s) { + return s.toLowerCase(java.util.Locale.ROOT).replaceAll("[^a-z0-9]", ""); + } + + private static final Pattern WS = Pattern.compile("(?U)\\s+"); + + private static String oneLine(String text) { + return WS.matcher(text).replaceAll(" ").strip(); + } + + private static String headingLine(Map r) { + String path = (String) r.get("path"); + String title = r.containsKey("title") ? oneLine((String) r.get("title")) : ""; + boolean restates = normalize(path.substring(path.lastIndexOf('.') + 1)).equals(normalize(title)); + String label = title.isEmpty() || restates ? "" : " — " + title; + return heading((Integer) r.get("depth")) + " " + path + label; + } + + private static String facts(Map r) { + List parts = new ArrayList<>(); + parts.add("`" + r.get("subType") + "`"); + if (r.containsKey("level")) parts.add("**L" + r.get("level") + "**"); + if (r.containsKey("status")) parts.add("status: `" + r.get("status") + "`"); + if (r.containsKey("disposition")) parts.add("disposition: `" + r.get("disposition") + "`"); + List tracked = list(r.get("trackedBy")); + if (!tracked.isEmpty()) parts.add("tracked: " + String.join(", ", tracked)); + return String.join(" · ", parts); + } + + private static final Pattern HEADING_LINE = Pattern.compile("(?m)^(#{1,6}) "); + + /** One extra {@code #} on every line that starts a heading, capped at h6. */ + private static String demote(String text) { + return HEADING_LINE.matcher(text).replaceAll(m -> + java.util.regex.Matcher.quoteReplacement("#".repeat(Math.min(m.group(1).length() + 1, 6)) + " ")); + } + + private static Map entryOf(Map r, boolean embedded) { + Function line = embedded ? DocsViewPages::demote : s -> s; + Map e = new LinkedHashMap<>(); + e.put("heading", line.apply(headingLine(r))); + e.put("facts", line.apply(facts(r))); + if (r.containsKey("statement")) e.put("statement", line.apply((String) r.get("statement"))); + if (r.containsKey("counterexample")) e.put("counterexample", line.apply("**Counterexample:** " + r.get("counterexample"))); + if (r.containsKey("description")) e.put("description", line.apply((String) r.get("description"))); + List impl = list(r.get("implementedBy")); + if (!impl.isEmpty()) { + List quoted = new ArrayList<>(); + for (String c : impl) quoted.add("`" + c + "`"); + e.put("implementedBy", line.apply("**Implemented by:** " + String.join(", ", quoted))); + } + return e; + } + + /** The data {@code requirements/requirements.md.mustache} renders, for a non-empty ledger. */ + public static Map requirementsLedgerData(List> rows, boolean embedded) { + Map d = new LinkedHashMap<>(); + d.put("embedded", embedded); + d.put("count", rows.size()); + d.put("plural", rows.size() == 1 ? "" : "s"); + List> entries = new ArrayList<>(); + for (Map r : rows) entries.add(entryOf(r, embedded)); + d.put("entries", entries); + return d; + } + + // ---- requirements.toon --------------------------------------------------------------- + + private static final List TOON_FIELDS = + List.of("path", "subType", "level", "status", "disposition", "claims", "statement"); + private static final Pattern NUMERIC_LIKE = Pattern.compile("-?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?"); + private static final Pattern LEADING_ZERO = Pattern.compile("0[0-9]+"); + private static final Pattern TOON_UNSAFE = Pattern.compile("[:\"\\\\\\[\\]{},\\x00-\\x1f]"); + + /** One cell as TOON writes it in a comma-delimited row: a number bare, a string bare when safe + * and quoted (with TOON's escapes) when it is empty, padded, numeric- or literal-looking, or + * carries a delimiter, a colon, a quote, a bracket, a leading {@code -} or a control character. */ + public static String toonCell(Object value) { + if (value instanceof Integer) return value.toString(); + String s = (String) value; + boolean safe = !s.isEmpty() && s.equals(s.strip()) + && !s.equals("true") && !s.equals("false") && !s.equals("null") + && !NUMERIC_LIKE.matcher(s).matches() && !LEADING_ZERO.matcher(s).matches() + && !TOON_UNSAFE.matcher(s).find() && !s.startsWith("-"); + if (safe) return s; + StringBuilder out = new StringBuilder("\""); + for (int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + switch (ch) { + case '\\' -> out.append("\\\\"); + case '"' -> out.append("\\\""); + case '\n' -> out.append("\\n"); + case '\r' -> out.append("\\r"); + case '\t' -> out.append("\\t"); + default -> { + if (ch < 0x20) out.append(String.format("\\u%04x", (int) ch)); + else out.append(ch); + } + } + } + return out.append('"').toString(); + } + + /** The data {@code requirements/requirements.toon.mustache} renders: every cell a finished literal. */ + public static Map requirementsToonData(List> rows) { + Map d = new LinkedHashMap<>(); + d.put("count", rows.size()); + d.put("fields", "{" + String.join(",", TOON_FIELDS) + "}"); + List> out = new ArrayList<>(); + for (Map r : rows) { + List cells = new ArrayList<>(); + cells.add(toonCell(r.get("path"))); + cells.add(toonCell(r.get("subType"))); + cells.add(toonCell(r.containsKey("level") ? r.get("level") : "")); + cells.add(toonCell(r.getOrDefault("status", ""))); + cells.add(toonCell(r.getOrDefault("disposition", ""))); + cells.add(toonCell(String.join(" ", list(r.get("implementedBy"))))); + cells.add(toonCell(r.getOrDefault("statement", ""))); + Map row = new LinkedHashMap<>(); + row.put("line", String.join(",", cells)); + out.add(row); + } + d.put("rows", out); + return d; + } + + // ---- agent/requirements.md ----------------------------------------------------------- + + private record Claim(String path, String subType, Integer level, String status, String statement) {} + + /** Claimed node to the requirements that claim it, sorted by the node's id. A claim that does + * not resolve is left out, as {@code meta verify} is what reports it. */ + private static List>> nodeIndex(JsonObject view, Predicate inLedger) { + Map head = new TreeMap<>(); + Map> claims = new TreeMap<>(); + for (JsonObject r : objects(arr(view, "requirements"))) { + if (inLedger != null && !inLedger.test(str(r, "qualifiedPath"))) continue; + for (JsonObject link : objects(arr(r, "implementedBy"))) { + if (!link.get("resolves").getAsBoolean()) continue; + JsonObject target = link.getAsJsonObject("target"); + String id = str(target, "id"); + head.putIfAbsent(id, new String[]{id, str(target, "kind")}); + claims.computeIfAbsent(id, k -> new ArrayList<>()).add(new Claim( + str(r, "address"), str(r, "subType"), has(r, "level") ? r.get("level").getAsInt() : null, + opt(str(r, "status")), opt(str(r, "statement")))); + } + } + List>> out = new ArrayList<>(); + for (Map.Entry e : head.entrySet()) out.add(Map.entry(e.getValue(), claims.get(e.getKey()))); + return out; + } + + /** The data {@code agent/requirements.md.mustache} renders; null for a model declaring no + * requirements, which gets no page. {@code renderLedger} renders the ledger template from its data. */ + public static Map agentRequirementsPageData( + JsonObject view, Predicate inLedger, Function, String> renderLedger) { + List> rows = requirementRows(view, inLedger); + if (rows.isEmpty()) return null; + List>> index = nodeIndex(view, inLedger); + Map stated = new TreeMap<>(); + for (Map.Entry> e : index) { + for (Claim c : e.getValue()) if (c.statement() != null) stated.put(c.path(), c); + } + List> statements = new ArrayList<>(); + for (Map.Entry e : stated.entrySet()) { + Map s = new LinkedHashMap<>(); + s.put("path", e.getKey()); + s.put("subType", e.getValue().subType()); + s.put("statement", oneLine(e.getValue().statement()).replace("|", "\\|")); + statements.add(s); + } + List> nodes = new ArrayList<>(); + for (Map.Entry> e : index) { + List cells = new ArrayList<>(); + for (Claim c : e.getValue()) { + String level = c.level() == null ? "" : " L" + c.level(); + String status = c.status() == null ? "" : " (" + c.status() + ")"; + cells.add("`" + c.path() + "`" + level + status); + } + Map n = new LinkedHashMap<>(); + n.put("address", e.getKey()[0]); + n.put("concern", e.getKey()[1]); + n.put("claims", String.join("
    ", cells)); + nodes.add(n); + } + Map d = new LinkedHashMap<>(); + d.put("generatedMarker", AGENT_PAGE_MARKER); + d.put("hasNodeIndex", !index.isEmpty()); + d.put("nodeIndex", nodes); + d.put("hasStatements", !statements.isEmpty()); + d.put("statements", statements); + d.put("ledger", stripTrailingNewlines(renderLedger.apply(requirementsLedgerData(rows, true)))); + return d; + } + + public static String stripTrailingNewlines(String s) { + int end = s.length(); + while (end > 0 && s.charAt(end - 1) == '\n') end--; + return s.substring(0, end); + } + + /** The text ending with exactly one of its own line breaks; text that ends without one is returned as is. */ + public static String keepOneTrailingNewline(String s) { + int end = s.length(); + while (end > 1 && s.charAt(end - 1) == '\n' && s.charAt(end - 2) == '\n') end--; + return s.substring(0, end); + } + + // ---- schema ------------------------------------------------------------------------ + + private static String storageKey(String name, String schema) { + return schema.isEmpty() ? name : schema + "." + name; + } + + private static List strings(JsonArray a) { + List out = new ArrayList<>(); + for (JsonElement e : a) out.add(e.getAsString()); + return out; + } + + /** The rows layer of the schema page, read off the view's storage ({@code expected/rows/schema.json}). */ + public static Map schemaRows(JsonObject view) { + JsonObject storage = view.getAsJsonObject("storage"); + Map declared = new TreeMap<>(); + List> tables = new ArrayList<>(); + for (JsonObject t : objects(arr(storage, "tables"))) { + declared.put(storageKey(str(t, "name"), str(t, "schema")), str(t.getAsJsonObject("declaredBy"), "id")); + Map row = new LinkedHashMap<>(); + row.put("name", str(t, "name")); + if (!str(t, "schema").isEmpty()) row.put("schema", str(t, "schema")); + if (!str(t, "description").isEmpty()) row.put("description", str(t, "description")); + row.put("primaryKey", strings(arr(t, "primaryKey"))); + List> columns = new ArrayList<>(); + for (JsonObject c : objects(arr(t, "columns"))) { + Map col = new LinkedHashMap<>(); + col.put("name", str(c, "name")); + col.put("nullable", c.get("nullable").getAsBoolean()); + if (!str(c, "identity").isEmpty()) col.put("identity", str(c, "identity")); + if (!str(c, "description").isEmpty()) col.put("description", str(c, "description")); + columns.add(col); + } + row.put("columns", columns); + List> fks = new ArrayList<>(); + for (JsonObject f : objects(arr(t, "foreignKeys"))) { + Map fk = new LinkedHashMap<>(); + fk.put("columns", strings(arr(f, "columns"))); + fk.put("refTable", str(f, "refTable")); + fk.put("refColumns", strings(arr(f, "refColumns"))); + fks.add(fk); + } + row.put("foreignKeys", fks); + tables.add(row); + } + List> views = new ArrayList<>(); + for (JsonObject v : objects(arr(storage, "views"))) { + declared.put(storageKey(str(v, "name"), str(v, "schema")), str(v.getAsJsonObject("declaredBy"), "id")); + Map row = new LinkedHashMap<>(); + row.put("name", str(v, "name")); + if (!str(v, "schema").isEmpty()) row.put("schema", str(v, "schema")); + views.add(row); + } + Map out = new LinkedHashMap<>(); + out.put("tables", tables); + out.put("views", views); + out.put("declaredBy", new LinkedHashMap<>(declared)); + return out; + } + + /** Every member of every node, by id. */ + private static Map membersById(JsonObject view) { + Map out = new LinkedHashMap<>(); + for (JsonObject n : objects(arr(view, "nodes"))) for (JsonObject g : objects(arr(n, "memberGroups"))) { + for (JsonObject m : objects(arr(g, "members"))) visit(m, out); + } + return out; + } + + private static void visit(JsonObject m, Map out) { + out.put(str(m, "id"), m); + for (JsonObject g : objects(arr(m, "memberGroups"))) for (JsonObject c : objects(arr(g, "members"))) visit(c, out); + } + + private static List directMembers(JsonObject n, String type) { + for (JsonObject g : objects(arr(n, "memberGroups"))) if (type.equals(str(g, "type"))) return objects(arr(g, "members")); + return List.of(); + } + + private static JsonObject attr(JsonObject owner, String name) { + for (JsonObject a : objects(arr(owner, "attrs"))) if (name.equals(str(a, "name"))) return a; + return null; + } + + private static JsonElement attrValue(JsonObject owner, String name) { + JsonObject a = attr(owner, name); + return a == null || !a.has("value") ? null : a.get("value"); + } + + /** A string attribute as a page prints it: a resolved reference by its link's label, anything else as its text. */ + private static String attrText(JsonObject owner, String name) { + JsonObject a = attr(owner, name); + if (a == null || !a.has("value") || !a.get("value").isJsonPrimitive() || !a.get("value").getAsJsonPrimitive().isString()) return null; + String text = a.get("value").getAsString(); + JsonArray values = arr(a, "values"); + if (values.size() > 0 && values.get(0).isJsonObject()) { + JsonElement link = values.get(0).getAsJsonObject().get("link"); + if (link != null && link.isJsonObject() && !link.getAsJsonObject().get("unresolved").getAsBoolean()) { + text = str(link.getAsJsonObject(), "label"); + } + } + return text.isEmpty() ? null : text; + } + + private static String cols(List names) { + if (names.isEmpty()) return NO_VALUE; + List q = new ArrayList<>(); + for (String c : names) q.add("`" + c + "`"); + return String.join(", ", q); + } + + private static String keyCell(JsonObject table, String column) { + List pk = strings(arr(table, "primaryKey")); + List roles = new ArrayList<>(); + if (pk.contains(column)) roles.add(pk.size() > 1 ? "PK (composite)" : "PK"); + for (JsonObject f : objects(arr(table, "foreignKeys"))) { + if (strings(arr(f, "columns")).contains(column)) { + roles.add("FK → `" + str(f, "refTable") + "`"); + break; + } + } + return String.join(" · ", roles); + } + + /** The lineage text of a view column, from its field's {@code origin.*} member. */ + private static String lineageOf(JsonObject field) { + if (field == null) return null; + List origins = directMembers(field, TYPE_ORIGIN); + if (origins.isEmpty()) return null; + JsonObject origin = origins.get(0); + String via = attrText(origin, "via"); + String of = attrText(origin, "of"); + String viaPart = via == null ? "" : " via `" + via + "`"; + switch (str(origin, "subType")) { + case "passthrough": { + String from = attrText(origin, "from"); + return "passthrough from `" + (from == null ? "?" : from) + "`" + viaPart; + } + case "aggregate": { + String agg = attrText(origin, "agg"); + return "`" + (agg == null ? "?" : agg) + "`" + (of == null ? "" : " of `" + of + "`") + viaPart; + } + case "first": { + String orderBy = attrText(origin, "orderBy"); + return "first" + (of == null ? "" : " `" + of + "`") + viaPart + + (orderBy == null ? "" : " ordered by `" + orderBy + "`"); + } + case "computed": + return "computed from a declared `@expr`"; + default: + return "`origin." + str(origin, "subType") + "`"; + } + } + + private static String cardinalityPhrase(JsonElement cardinality, String through) { + String c = cardinality != null && cardinality.isJsonPrimitive() ? cardinality.getAsString() : null; + if ("many".equals(c)) return through != null ? "many-to-many" : "one-to-many"; + if ("one".equals(c)) return "many-to-one"; + return "cardinality not declared"; + } + + /** + * The data {@code agent/schema.md.mustache} renders for the model-only page, built from the view + * alone. {@code hasMigrate}: the project chose a {@code meta migrate} dialect. Null when the model + * declares no table and no view: no page. + */ + public static Map agentSchemaPageData(JsonObject view, boolean hasMigrate) { + JsonObject storage = view.getAsJsonObject("storage"); + List tables = objects(arr(storage, "tables")); + List views = objects(arr(storage, "views")); + if (tables.isEmpty() && views.isEmpty()) return null; + Map members = membersById(view); + List byOrder = new ArrayList<>(objects(arr(view, "nodes"))); + byOrder.sort(Comparator.comparingInt(n -> n.get("order").getAsInt())); + + List> tableData = new ArrayList<>(); + for (JsonObject t : tables) { + List columns = objects(arr(t, "columns")); + List described = new ArrayList<>(); + for (JsonObject c : columns) if (!str(c, "description").isEmpty()) described.add(c); + List fks = new ArrayList<>(); + for (JsonObject f : objects(arr(t, "foreignKeys"))) { + fks.add(cols(strings(arr(f, "columns"))) + " → `" + str(f, "refTable") + "`(" + cols(strings(arr(f, "refColumns"))) + ")"); + } + Map td = new LinkedHashMap<>(); + td.put("heading", "`" + storageKey(str(t, "name"), str(t, "schema")) + "`"); + td.put("tableDeclaredBy", str(t.getAsJsonObject("declaredBy"), "id")); + if (!str(t, "description").isEmpty()) td.put("tableDescription", oneLine(str(t, "description"))); + List> cd = new ArrayList<>(); + for (JsonObject c : columns) { + JsonObject field = has(c, "field") ? c.getAsJsonObject("field") : null; + Map col = new LinkedHashMap<>(); + col.put("name", str(c, "name")); + col.put("fieldCell", field == null ? "" : "`" + (members.containsKey(str(field, "id")) ? str(members.get(str(field, "id")), "name") : "") + "`"); + col.put("declaredCell", field == null ? "" : "`" + str(field, "kind") + "`"); + col.put("sqlTypeCell", ""); + col.put("nullCell", c.get("nullable").getAsBoolean() ? "yes" : "no"); + col.put("defaultCell", ""); + col.put("keyCell", keyCell(t, str(c, "name"))); + cd.add(col); + } + td.put("columns", cd); + td.put("hasDescribed", !described.isEmpty()); + List> dd = new ArrayList<>(); + for (JsonObject c : described) { + Map d = new LinkedHashMap<>(); + d.put("name", str(c, "name")); + d.put("text", oneLine(str(c, "description"))); + dd.add(d); + } + td.put("described", dd); + td.put("hasIndexes", false); + td.put("indexes", new ArrayList<>()); + td.put("hasForeignKeys", !fks.isEmpty()); + td.put("foreignKeys", fks); + td.put("hasChecks", false); + td.put("checks", new ArrayList<>()); + tableData.add(td); + } + + List> viewData = new ArrayList<>(); + for (JsonObject v : views) { + List> lineage = new ArrayList<>(); + for (JsonObject c : objects(arr(v, "columns"))) { + JsonObject field = has(c, "field") ? members.get(str(c.getAsJsonObject("field"), "id")) : null; + String text = lineageOf(field); + if (text == null) continue; + Map l = new LinkedHashMap<>(); + l.put("column", str(c, "name")); + l.put("text", text); + lineage.add(l); + } + Map vd = new LinkedHashMap<>(); + vd.put("heading", "`" + storageKey(str(v, "name"), str(v, "schema")) + "`"); + vd.put("viewDeclaredBy", str(v.getAsJsonObject("declaredBy"), "id")); + vd.put("hasLineage", !lineage.isEmpty()); + vd.put("lineage", lineage); + viewData.add(vd); + } + + // Every relationship as written, in declaration order of its object. + List relationships = new ArrayList<>(); + for (JsonObject n : byOrder) { + if (!TYPE_OBJECT.equals(str(n, "type"))) continue; + for (JsonObject rel : directMembers(n, TYPE_RELATIONSHIP)) { + String through = attrText(rel, "through"); + String onDelete = attrText(rel, "onDelete"); + String objectRef = attrText(rel, "objectRef"); + List parts = new ArrayList<>(); + parts.add("`" + str(n, "id") + "." + str(rel, "name") + "`"); + parts.add("`" + str(rel, "subType") + "`"); + parts.add(cardinalityPhrase(attrValue(rel, "cardinality"), through) + " → `" + (objectRef == null ? "?" : objectRef) + "`"); + if (through != null) parts.add("through `" + through + "`"); + if (onDelete != null) parts.add("on delete `" + onDelete + "`"); + relationships.add(String.join(" · ", parts)); + } + } + + // Every enum field of a table-backed object, in declaration order of its object. + Set tableBacked = new LinkedHashSet<>(); + for (JsonObject t : tables) for (JsonObject o : objects(arr(t, "objects"))) tableBacked.add(str(o, "id")); + List> enums = new ArrayList<>(); + for (JsonObject n : byOrder) { + if (!tableBacked.contains(str(n, "id"))) continue; + for (JsonObject f : directMembers(n, TYPE_FIELD)) { + if (!SUBTYPE_ENUM.equals(str(f, "subType"))) continue; + JsonElement values = attrValue(f, "values"); + List list = new ArrayList<>(); + if (values != null && values.isJsonArray()) for (JsonElement v : values.getAsJsonArray()) list.add(jsString(v)); + if (list.isEmpty()) continue; + JsonElement intMap = attrValue(f, "intValueMap"); + String storageText; + if (intMap != null && intMap.isJsonObject()) { + List pairs = new ArrayList<>(); + for (String m : list) { + JsonElement v = intMap.getAsJsonObject().get(m); + pairs.add(m + "=" + (v == null ? "undefined" : jsString(v))); + } + storageText = "int-backed (" + String.join(", ", pairs) + ")"; + } else { + storageText = "string-backed"; + } + List quoted = new ArrayList<>(); + for (String m : list) quoted.add("`" + m + "`"); + Map e = new LinkedHashMap<>(); + e.put("field", str(n, "id") + "." + str(f, "name")); + e.put("members", String.join(", ", quoted)); + e.put("storage", storageText); + enums.add(e); + } + } + + boolean anyDescription = false; + for (JsonObject t : tables) { + if (!str(t, "description").isEmpty()) anyDescription = true; + for (JsonObject c : objects(arr(t, "columns"))) if (!str(c, "description").isEmpty()) anyDescription = true; + } + boolean reportView = false; + for (JsonObject v : views) for (JsonObject o : objects(arr(v, "objects"))) if (KIND_REPORT.equals(str(o, "kind"))) reportView = true; + + Map d = new LinkedHashMap<>(); + d.put("generatedMarker", AGENT_PAGE_MARKER); + d.put("physical", false); + d.put("dialect", ""); + d.put("hasMigrate", hasMigrate); + d.put("descriptionNudge", !anyDescription && !tables.isEmpty()); + d.put("hasTables", !tableData.isEmpty()); + d.put("tables", tableData); + d.put("hasViews", !viewData.isEmpty()); + d.put("hasReportView", reportView); + d.put("views", viewData); + d.put("hasRelationships", !relationships.isEmpty()); + d.put("relationships", relationships); + d.put("hasEnums", !enums.isEmpty()); + d.put("enums", enums); + return d; + } + + /** {@code String(v)} of a JSON scalar as JavaScript prints it. */ + private static String jsString(JsonElement v) { + if (v.isJsonPrimitive()) { + JsonPrimitive p = v.getAsJsonPrimitive(); + return p.getAsString(); + } + return v.toString(); + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java new file mode 100644 index 0000000000..6089ece396 --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java @@ -0,0 +1,63 @@ +package com.metaobjects.generator; + +// Eject note (ADR-0034 Amendment 8): `mvn metaobjects:eject -Dnames=agent-docs` copies this file. +// What there is to emit (the page data) and the templates stay in com.metaobjects.docs.pages and on the +// classpath, so the copy can change where the pages go and how they are laid out, and a project that wants +// other page text puts a same-path template earlier on the classpath or names a `templateDir`. +import com.google.gson.JsonObject; +import com.metaobjects.config.MigrateSettings; +import com.metaobjects.config.SourceResolver; +import com.metaobjects.docs.pages.DocsPagesEmitter; +import com.metaobjects.docsview.DocsView; +import com.metaobjects.generator.FileEmittingGenerator; +import com.metaobjects.loader.MetaDataLoader; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * {@code agent-docs}: pages written for a coding agent working in the project, rendered from the + * shared {@code templates/agent/} Mustache pages over the model's docs view: {@code agent/requirements.md} + * (the node index and the ledger) and the model-only {@code agent/schema.md} (tables, views, + * relationships and enums, without the SQL types, defaults, indexes and checks the model cannot know). + * {@code agent/ui.md} stays a TypeScript page. No requirement, no requirement page; no table and no + * view, no schema page. + * + *

    Args: {@code outputDir} (required), {@code subDir} (where under it the pages land, default empty: + * the root) and {@code templateDir} (a directory holding {@code agent/.mustache} and + * {@code requirements/.mustache} overrides). The schema page says to change the schema with + * {@code meta migrate} when the project's {@code .metaobjects/config.json} sets {@code migrate.dialect}. + * Give it an {@code outputDir} that holds generated files only.

    + */ +public class AgentDocsGenerator extends FileEmittingGenerator { + + /** Arg: where under {@code outputDir} the pages land. */ + public static final String ARG_SUB_DIR = "subDir"; + + /** Arg: a directory holding {@code agent/.mustache} that win over the packaged templates. */ + public static final String ARG_TEMPLATE_DIR = "templateDir"; + + @Override + protected List generate(MetaDataLoader loader) { + String subDir = getArg(ARG_SUB_DIR, ""); + Path templateDir = hasArg(ARG_TEMPLATE_DIR) ? Path.of(getArg(ARG_TEMPLATE_DIR)) : null; + JsonObject view = DocsView.build(loader.getRoot()); + List files = new ArrayList<>(); + for (Map.Entry page : DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, null).entrySet()) { + files.add(new EmittedFile(page.getKey(), page.getValue())); + } + return files; + } + + /** The project chose a {@code meta migrate} dialect: its config sets {@code migrate.dialect}. */ + private static boolean choseMigrateDialect(MetaDataLoader loader) { + MigrateSettings settings = MigrateSettings.of(loader.getRoot()); + if (settings.getDialect() != null) return true; + if (loader.getSourceURIs() == null) return false; + Optional found = SourceResolver.discoverMigrateSettings(loader.getSourceURIs()); + return found.isPresent() && found.get().getDialect() != null; + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java new file mode 100644 index 0000000000..65f3bf30ab --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java @@ -0,0 +1,47 @@ +package com.metaobjects.generator; + +// Eject note (ADR-0034 Amendment 8): `mvn metaobjects:eject -Dnames=requirements` copies this file. +// What there is to emit (the page data) and the template stay in com.metaobjects.docs.pages and on the +// classpath, so the copy can change where the page goes and how it is laid out, and a project that wants +// other page text puts a same-path template earlier on the classpath or names a `templateDir`. +import com.google.gson.JsonObject; +import com.metaobjects.docs.pages.DocsPagesEmitter; +import com.metaobjects.docsview.DocsView; +import com.metaobjects.generator.FileEmittingGenerator; +import com.metaobjects.loader.MetaDataLoader; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * {@code requirements}: the requirement ledger as {@code requirements.toon}, for tools, rendered from + * the shared {@code templates/requirements/} Mustache page over the model's docs view. People read the + * ledger in the explorer ({@code docs-site}). A model that declares no {@code requirement.*} node + * gets no file. + * + *

    Args: {@code outputDir} (required), {@code subDir} (where under it the page lands, default empty: + * the root) and {@code templateDir} (a directory holding {@code requirements/.mustache} + * overrides). Give it an {@code outputDir} that holds generated files only.

    + */ +public class RequirementsGenerator extends FileEmittingGenerator { + + /** Arg: where under {@code outputDir} the page lands. */ + public static final String ARG_SUB_DIR = "subDir"; + + /** Arg: a directory holding {@code requirements/.mustache} that win over the packaged templates. */ + public static final String ARG_TEMPLATE_DIR = "templateDir"; + + @Override + protected List generate(MetaDataLoader loader) { + String subDir = getArg(ARG_SUB_DIR, ""); + Path templateDir = hasArg(ARG_TEMPLATE_DIR) ? Path.of(getArg(ARG_TEMPLATE_DIR)) : null; + JsonObject view = DocsView.build(loader.getRoot()); + List files = new ArrayList<>(); + for (Map.Entry page : DocsPagesEmitter.requirementsPages(view, subDir, templateDir, null).entrySet()) { + files.add(new EmittedFile(page.getKey(), page.getValue())); + } + return files; + } +} diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java index 7bf774c180..2109e20b5e 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java @@ -62,10 +62,10 @@ public void modelScriptIsTypeScriptsBytes() throws Exception { Map.of("explorer-head.mustache", ""), expectedView("shop")); // explorerModelScript({ title: "Shop 
", footer: "v1", texts, templates, view }) // in @metaobjectsdev/docs-site, over the same shop view, gives this stamp and these bytes. - assertEquals("05b57283a47416e2", m.stamp()); - assertEquals(50657, m.script().length()); - assertEquals("02f2d4321101c0ab9fa9e22db542ff8f71f1e952748e8f894d388bd43feeb6bc", sha256(m.script())); - assertEquals("window.MO_STAMP = \"05b57283a47416e2\";\n", ExplorerSite.stampScript(m.stamp())); + assertEquals("33fd741544d5a480", m.stamp()); + assertEquals(55371, m.script().length()); + assertEquals("c649aa99ef4c570149d6ce06f102738524db766915829a889b39f884af061070", sha256(m.script())); + assertEquals("window.MO_STAMP = \"33fd741544d5a480\";\n", ExplorerSite.stampScript(m.stamp())); } @Test diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java new file mode 100644 index 0000000000..3a0b88b755 --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java @@ -0,0 +1,151 @@ +package com.metaobjects.docs.pages; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.docsview.DocsView; +import com.metaobjects.loader.DirectorySource; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import org.junit.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * The docs page corpus ({@code fixtures/docs-page-conformance/}): for each case the model in + * {@code input/} is loaded, its docs view is built with no verify ledger, manifest or routes, and + * the builders over that view must reproduce, in order, the rows ({@code expected/rows/}), the page + * data ({@code expected/data/}) and the page bytes, over exactly the expected file set. The + * TypeScript generators are the source of the expected bytes. + */ +public class DocsPageConformanceTest { + + private static final Gson GSON = new Gson(); + + private static Path corpus() { + for (Path p = Path.of("").toAbsolutePath(); p != null; p = p.getParent()) { + Path c = p.resolve("fixtures/docs-page-conformance/cases"); + if (Files.isDirectory(c)) return c; + } + throw new IllegalStateException("fixtures/docs-page-conformance/cases not found above " + Path.of("").toAbsolutePath()); + } + + private static JsonObject viewOf(Path input, String name) { + LoaderOptions opts = LoaderOptions.create(false, false, true); + MetaDataLoader loader = new MetaDataLoader(opts, MetaDataLoader.SUBTYPE_MANUAL, "docs_page_" + name.replace('-', '_')); + loader.init(); + // Top level only: the case's .metaobjects/config.json is project state, not metadata. + loader.load(new DirectorySource(input, new DirectorySource.Options().setRecurse(false)).expandToList()); + assertTrue(name + ": expected a clean strict load, got: " + loader.getErrors(), loader.getErrors().isEmpty()); + return DocsView.build(loader.getRoot()); + } + + /** The case chose a {@code meta migrate} dialect: its config sets {@code migrate.dialect}. */ + private static boolean choseMigrateDialect(Path input) throws IOException { + Path config = input.resolve(".metaobjects/config.json"); + if (!Files.isRegularFile(config)) return false; + JsonObject root = JsonParser.parseString(Files.readString(config, StandardCharsets.UTF_8)).getAsJsonObject(); + return root.has("migrate") && root.getAsJsonObject("migrate").has("dialect"); + } + + private static Map expectedOf(Path dir) throws IOException { + Map out = new TreeMap<>(); + if (!Files.isDirectory(dir)) return out; + try (Stream s = Files.walk(dir)) { + for (Path p : s.filter(Files::isRegularFile).toList()) { + out.put(dir.relativize(p).toString().replace('\\', '/'), Files.readString(p, StandardCharsets.UTF_8)); + } + } + return out; + } + + private static void assertJson(String what, String expected, Object actual) { + assertEquals(what, JsonParser.parseString(expected), GSON.toJsonTree(actual)); + } + + private static List cases() throws IOException { + List out = new ArrayList<>(); + try (Stream s = Files.list(corpus())) { + s.filter(Files::isDirectory).map(p -> p.getFileName().toString()).sorted().forEach(out::add); + } + return out; + } + + @Test + public void everyCaseReproducesRowsDataAndBytes() throws IOException { + List names = cases(); + assertTrue("the corpus is not empty", !names.isEmpty()); + for (String name : names) { + Path caseDir = corpus().resolve(name); + Path input = caseDir.resolve("input"); + JsonObject view = viewOf(input, name); + boolean migrate = choseMigrateDialect(input); + Map expected = expectedOf(caseDir.resolve("expected")); + + Map actual = new TreeMap<>(); + // 1. rows, 2. page data + List> rows = DocsViewPages.requirementRows(view, null); + if (!rows.isEmpty()) { + assertJson(name + " rows/requirements.json", expected.get("rows/requirements.json"), rows); + assertJson(name + " data/ledger.md.json", expected.get("data/ledger.md.json"), DocsViewPages.requirementsLedgerData(rows, true)); + assertJson(name + " data/requirements.toon.json", expected.get("data/requirements.toon.json"), DocsViewPages.requirementsToonData(rows)); + actual.put("rows/requirements.json", ""); + actual.put("data/ledger.md.json", ""); + actual.put("data/requirements.toon.json", ""); + } + Map agentRequirements = DocsViewPages.agentRequirementsPageData(view, null, ledger -> ""); + if (agentRequirements != null) { + // The ledger is the rendered embedded template; compare the data through the real renderer. + Map pages = DocsPagesEmitter.agentPages(view, migrate, "", null, null); + actual.put("data/agent-requirements.md.json", ""); + assertTrue(name + ": agent/requirements.md written", pages.containsKey("agent/requirements.md")); + } + Map schema = DocsViewPages.agentSchemaPageData(view, migrate); + if (schema != null) { + assertJson(name + " rows/schema.json", expected.get("rows/schema.json"), DocsViewPages.schemaRows(view)); + assertJson(name + " data/agent-schema.md.json", expected.get("data/agent-schema.md.json"), schema); + actual.put("rows/schema.json", ""); + actual.put("data/agent-schema.md.json", ""); + } + + // 3. bytes + Map pages = new TreeMap<>(); + pages.putAll(DocsPagesEmitter.requirementsPages(view, "", null, null)); + pages.putAll(DocsPagesEmitter.agentPages(view, migrate, "", null, null)); + actual.putAll(pages); + + // The agent requirements data carries the rendered ledger: check it against the pinned data too. + if (agentRequirements != null) { + Map real = DocsViewPages.agentRequirementsPageData(view, null, + ledger -> renderLedger(ledger)); + assertJson(name + " data/agent-requirements.md.json", expected.get("data/agent-requirements.md.json"), real); + } + + // the SET of files is pinned too: a file one side writes and the other does not is drift + assertEquals(name + ": file set", new TreeSet<>(expected.keySet()), new TreeSet<>(actual.keySet())); + for (Map.Entry page : pages.entrySet()) { + assertEquals(name + ": " + page.getKey(), expected.get(page.getKey()), page.getValue()); + } + } + } + + private static String renderLedger(Map ledgerData) { + return new com.metaobjects.render.Renderer().render(new com.metaobjects.render.RenderRequest( + null, DocsViewPages.REQUIREMENTS_LEDGER_REF, ledgerData, + com.metaobjects.docs.metamodel.MetamodelDocsEmitter.provider(null, DocsPageConformanceTest.class.getClassLoader()), + com.metaobjects.render.Escapers.FORMAT_MARKDOWN, null, null)); + } +} diff --git a/server/java/codegen-kotlin/pom.xml b/server/java/codegen-kotlin/pom.xml index 353e269bc3..548a7b8d2e 100644 --- a/server/java/codegen-kotlin/pom.xml +++ b/server/java/codegen-kotlin/pom.xml @@ -258,6 +258,8 @@ KotlinReportExportGenerator.kt KotlinSharedModelGenerator.kt KotlinMetamodelDocsGenerator.kt + KotlinRequirementsGenerator.kt + KotlinAgentDocsGenerator.kt KotlinEnumEmitter.kt diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistry.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistry.kt index a217768522..3bd9859e25 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistry.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/GeneratorRegistry.kt @@ -313,6 +313,24 @@ val GENERATOR_REGISTRY: Map = linkedMapOf( factory = ::KotlinMetamodelDocsGenerator, ejectResourcePath = ejectPath("KotlinMetamodelDocsGenerator"), ), + "requirements" to GeneratorInfo( + name = "requirements", + description = "The requirement ledger as requirements.toon, for tools (a shared Mustache template over " + + "the docs view); people read it in the explorer (docs-site). No requirement.* node, no file.", + tier = GeneratorTier.NEUTRAL, + layer = GeneratorLayer.DOCS, + factory = ::KotlinRequirementsGenerator, + ejectResourcePath = ejectPath("KotlinRequirementsGenerator"), + ), + "agent-docs" to GeneratorInfo( + name = "agent-docs", + description = "Pages written for a coding agent: agent/requirements.md and the model-only agent/schema.md " + + "(shared Mustache templates over the docs view; agent/ui.md stays TypeScript-only).", + tier = GeneratorTier.NEUTRAL, + layer = GeneratorLayer.DOCS, + factory = ::KotlinAgentDocsGenerator, + ejectResourcePath = ejectPath("KotlinAgentDocsGenerator"), + ), // Exempt from eject (registry.json): the site builder is engine, and the site is language-neutral, // so Kotlin runs the JVM DocsSiteGenerator itself and writes the same bytes as Java. "docs-site" to GeneratorInfo( diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt new file mode 100644 index 0000000000..3a80e3b522 --- /dev/null +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt @@ -0,0 +1,50 @@ +package com.metaobjects.generator.kotlin + +import com.metaobjects.config.MigrateSettings +import com.metaobjects.config.SourceResolver +import com.metaobjects.docs.pages.DocsPagesEmitter +import com.metaobjects.docsview.DocsView +import com.metaobjects.generator.FileEmittingGenerator +import com.metaobjects.generator.FileEmittingGenerator.EmittedFile +import com.metaobjects.loader.MetaDataLoader +import java.nio.file.Path + +/** + * `agent-docs`: pages written for a coding agent working in the project, rendered from the shared + * `templates/agent/` Mustache pages over the model's docs view: `agent/requirements.md` (the node index and + * the ledger) and the model-only `agent/schema.md`. The Kotlin sibling of the JVM `AgentDocsGenerator`: the + * pages are language-neutral, so both write identical bytes. `agent/ui.md` stays a TypeScript page. No + * requirement, no requirement page; no table and no view, no schema page. + * + * This file decides where the pages go; what there is to emit (the page data) and the templates stay in the + * package, so a copy (`mvn metaobjects:eject`) can lay the pages out differently, and a project that wants + * other page text puts a same-path template earlier on the classpath or names a `templateDir`. The schema + * page says to change the schema with `meta migrate` when the project's `.metaobjects/config.json` sets + * `migrate.dialect`. + * + * Args: `outputDir` (required), `subDir` (where under it the pages land, default empty: the root) and + * `templateDir` (a directory holding `agent/.mustache` and `requirements/.mustache` overrides). + */ +open class KotlinAgentDocsGenerator : FileEmittingGenerator() { + + override fun generate(loader: MetaDataLoader): List { + val subDir = getArg(ARG_SUB_DIR, "") + val templateDir: Path? = if (hasArg(ARG_TEMPLATE_DIR)) Path.of(getArg(ARG_TEMPLATE_DIR)) else null + val view = DocsView.build(loader.root) + return DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, null) + .map { (path, content) -> EmittedFile(path, content) } + } + + /** The project chose a `meta migrate` dialect: its config sets `migrate.dialect`. */ + private fun choseMigrateDialect(loader: MetaDataLoader): Boolean { + if (MigrateSettings.of(loader.root).dialect != null) return true + val uris = loader.sourceURIs ?: return false + val found = SourceResolver.discoverMigrateSettings(uris) + return found.isPresent && found.get().dialect != null + } + + companion object { + const val ARG_SUB_DIR = "subDir" + const val ARG_TEMPLATE_DIR = "templateDir" + } +} diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementsGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementsGenerator.kt new file mode 100644 index 0000000000..492902ebec --- /dev/null +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementsGenerator.kt @@ -0,0 +1,36 @@ +package com.metaobjects.generator.kotlin + +import com.metaobjects.docs.pages.DocsPagesEmitter +import com.metaobjects.docsview.DocsView +import com.metaobjects.generator.FileEmittingGenerator +import com.metaobjects.generator.FileEmittingGenerator.EmittedFile +import com.metaobjects.loader.MetaDataLoader +import java.nio.file.Path + +/** + * `requirements`: the requirement ledger as `requirements.toon`, for tools, rendered from the shared + * `templates/requirements/` Mustache page over the model's docs view. The Kotlin sibling of the JVM + * `RequirementsGenerator`: the page is language-neutral, so both write identical bytes. People read the + * ledger in the explorer (`docs-site`). A model that declares no `requirement.*` node gets no file. + * + * This file decides where the page goes; what there is to emit (the page data) and the template stay in + * the package, so a copy (`mvn metaobjects:eject`) can lay the page out differently, and a project that + * wants other page text puts a same-path template earlier on the classpath or names a `templateDir`. + * + * Args: `outputDir` (required), `subDir` (where under it the page lands, default empty: the root) and + * `templateDir` (a directory holding `requirements/.mustache` overrides). + */ +open class KotlinRequirementsGenerator : FileEmittingGenerator() { + + override fun generate(loader: MetaDataLoader): List { + val subDir = getArg(ARG_SUB_DIR, "") + val templateDir: Path? = if (hasArg(ARG_TEMPLATE_DIR)) Path.of(getArg(ARG_TEMPLATE_DIR)) else null + val view = DocsView.build(loader.root) + return DocsPagesEmitter.requirementsPages(view, subDir, templateDir, null).map { (path, content) -> EmittedFile(path, content) } + } + + companion object { + const val ARG_SUB_DIR = "subDir" + const val ARG_TEMPLATE_DIR = "templateDir" + } +} diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ReportingInertTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ReportingInertTest.kt index 2dc1fa0bbf..dd2e999afb 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ReportingInertTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/ReportingInertTest.kt @@ -113,7 +113,7 @@ class ReportingInertTest { } /** - * Every generator that writes code. `api-docs` writes the api reference, not code, and is + * Every generator that writes code. `agent-docs` writes pages, held to its own test below. `api-docs` writes the api reference, not code, and is * held to the same inertness by [api docs gain exactly the view-backed report's page], which * compares its pages unit by unit. */ @@ -121,7 +121,25 @@ class ReportingInertTest { // which a bare in-memory model does not have. Its bytes are gated by the shared-model corpus. // docs-site documents every node, so it is held to its own line (DocsSiteInert), below. private val codeGenerators get() = GENERATOR_REGISTRY.values.filter { - it.name != "api-docs" && it.name != "shared-model" && it.name != DocsSiteInert.GENERATOR + it.name != "api-docs" && it.name != "agent-docs" && it.name != "shared-model" && it.name != DocsSiteInert.GENERATOR + } + + @Test + fun `agent docs list the view-backed report's view and no sourceless report`() { + // agent-docs writes pages, not code: its schema page lists every table and view, so the served + // report's view is one more entry there, and nothing else moves. + val info = GENERATOR_REGISTRY.getValue("agent-docs") + val without = emit("without", listOf(info)) + val with = emit("with", listOf(info)) + assertEquals(without.keys, with.keys) + val schema = "agent/schema.md" + assertTrue("StoreTotals" in with.getValue(schema), "the served report is not on the schema page") + assertFalse("StoreTotals" in without.getValue(schema), "the schema page names the report without it") + for (report in SOURCELESS_REPORTS) { + assertFalse(with.any { (path, text) -> report in path || report in text }, "$report is on an agent page") + } + val differing = without.keys.filter { it != schema && without[it] != with[it] } + assertTrue(differing.isEmpty(), "$differing differ once reporting nodes are declared") } @Test diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java index 8fd278bd95..2a9ccde4d4 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/GeneratorRegistry.java @@ -12,7 +12,9 @@ import com.metaobjects.generator.apidocs.JavaApiModelBuilder; import com.metaobjects.generator.apidocs.JavaFieldShapes; import com.metaobjects.generator.apidocs.UnitExample; +import com.metaobjects.generator.AgentDocsGenerator; import com.metaobjects.generator.MetamodelDocsGenerator; +import com.metaobjects.generator.RequirementsGenerator; import com.metaobjects.generator.direct.metadata.ai.MetaDataAIDocumentationGenerator; import com.metaobjects.generator.direct.metadata.ai.MetaDataAIDocumentationWriter; import com.metaobjects.generator.direct.metadata.file.json.MetaDataFileJsonSchemaGenerator; @@ -497,6 +499,14 @@ Tier.NATIVE, Layer.DOCS, ejectPath(JavaApiDocsGenerator.class), List.of(), null, + "by provider, rendered from the shared templates/metamodel/ Mustache set " + "(INDEX.md, providers.md, one types/.md per type family). Reads no model objects.", Tier.NEUTRAL, Layer.DOCS, ejectPath(MetamodelDocsGenerator.class)); + register(m, "requirements", RequirementsGenerator.class.getName(), + "The requirement ledger as requirements.toon, for tools (a shared Mustache template over " + + "the docs view); people read it in the explorer (docs-site). No requirement.* node, no file.", + Tier.NEUTRAL, Layer.DOCS, ejectPath(RequirementsGenerator.class)); + register(m, "agent-docs", AgentDocsGenerator.class.getName(), + "Pages written for a coding agent: agent/requirements.md and the model-only agent/schema.md " + + "(shared Mustache templates over the docs view; agent/ui.md stays TypeScript-only).", + Tier.NEUTRAL, Layer.DOCS, ejectPath(AgentDocsGenerator.class)); // Exempt from eject (registry.json): the site builder is engine; what a project changes is the // explorer's theme, which it owns under codegen/docs-site/ and this generator reads from there. register(m, "docs-site", DocsSiteGenerator.class.getName(), diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ReportingInertTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ReportingInertTest.java index 3d4966c6cb..d47c5b3189 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ReportingInertTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/ReportingInertTest.java @@ -83,11 +83,13 @@ public class ReportingInertTest extends SharedRegistryTestBase { /** * The files that LIST every unit rather than describe one, by generator stable name: the api - * reference's index and agent page. They differ between the two models by the served report's + * reference's index and agent page, and the agent schema page. They differ between the two models by the served report's * entry, so each is checked to name it and then left out of the byte comparison. */ private static final Map> UNIT_LISTINGS = Map.of( - "api-docs", List.of("api/java/README.md", "api/java/AGENT-API.md")); + "api-docs", List.of("api/java/README.md", "api/java/AGENT-API.md"), + // The agent schema page lists every table and view, and the served report reads one. + "agent-docs", List.of("agent/schema.md")); private static Path model(String variant) { return SpringTestFixtures.findCorpusRoot().getParent() diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratorWritePathTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratorWritePathTest.java index cd6a275700..a3d121c8e6 100644 --- a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratorWritePathTest.java +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratorWritePathTest.java @@ -140,7 +140,8 @@ private Map args(Entry e, Path outDir) { /** Generators keyed off model nodes the fitness corpus does not declare, so they write nothing over it. */ private static final List NO_INPUT_IN_CORPUS = - List.of("java-trace-helper", "java-requirement-tests", "kotlin-stored-proc", "kotlin-requirement-tests"); + List.of("java-trace-helper", "java-requirement-tests", "java-requirements", "kotlin-stored-proc", "kotlin-requirements", + "kotlin-requirement-tests"); /** What each run wrote: the files left on disk, and the paths the writer was asked for. */ private record Result(Map disk, Set emitted) {} diff --git a/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsView.java b/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsView.java index f7841a89cd..a902e99f5d 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsView.java +++ b/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsView.java @@ -606,6 +606,12 @@ JsonObject run(JsonElement verifyIn, JsonElement manifest, JsonElement routesIn) view.add("requirements", array(reqs)); view.add("advisories", advisories); view.add("slices", slices(nodes, reqs)); + view.add("storage", DocsViewStorage.build(root, DocsView::children, md -> linkTo(md, md.getName()), (owner, field) -> { + Walked top = canonical.get(owner); + if (top == null) return null; + for (Walked c : top.children) if (c.md == field) return link(c); + return null; + })); return view; } @@ -818,7 +824,7 @@ private static String plainOf(MetaData md) { return pkg.isEmpty() ? nameOf(md) : pkg + PKG + nameOf(md); } - private static boolean isAbstract(MetaData md) { + static boolean isAbstract(MetaData md) { // ADR-0039: own — @isAbstract is a declaration-layer marker, never inherited. return md.hasMetaAttr(MetaData.ATTR_IS_ABSTRACT, false) && Boolean.TRUE.equals(md.getMetaAttr(MetaData.ATTR_IS_ABSTRACT, false).getValue()); diff --git a/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsViewStorage.java b/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsViewStorage.java new file mode 100644 index 0000000000..7b2b3875c3 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsViewStorage.java @@ -0,0 +1,446 @@ +package com.metaobjects.docsview; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.metaobjects.MetaData; +import com.metaobjects.database.ColumnNaming; +import com.metaobjects.database.PhysicalNaming; +import com.metaobjects.documentation.DocumentationConstants; +import com.metaobjects.field.MetaField; +import com.metaobjects.field.ObjectField; +import com.metaobjects.identity.MetaIdentity; +import com.metaobjects.identity.ReferenceIdentity; +import com.metaobjects.loader.References; +import com.metaobjects.object.MetaObject; +import com.metaobjects.origin.MetaOrigin; +import com.metaobjects.source.MetaSource; +import com.metaobjects.source.SourceResolution; +import com.metaobjects.validator.MetaValidator; +import com.metaobjects.validator.RequiredValidator; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiFunction; +import java.util.function.Function; + +/** + * The docs view's {@code storage} section: the tables and views the model declares, named by this + * port's own naming helpers ({@code docs/features/docs-view.md}, "storage"). The Java port of + * TypeScript's {@code buildStorage} ({@code docs-view/storage.ts}), held to the same bytes by + * {@code fixtures/explorer-conformance/}. + * + *

    MODEL-ONLY: a table per concrete object whose primary source is a writable, managed table + * (abstract bases and sourceless values have none; a TPH subtype shares its base's table and adds + * its own columns after the base's, nullable), a view per object whose primary source is a view. + * The physical facts (SQL type, default, indexes, checks, constraint names, referential actions) + * are {@code null} here; only the TypeScript run fills them.

    + */ +final class DocsViewStorage { + + private DocsViewStorage() {} + + /** A column as the walk finds it, before its field link is attached. */ + private record RawColumn(String name, boolean nullable, String identity, String description) { + RawColumn withNullable(boolean n) { + return new RawColumn(name, n, identity, description); + } + } + + private record Mapped(MetaObject owner, MetaData field) {} + + /** + * @param children the effective structural children of a node (the walk's own accessor) + * @param node the link to a top-level node + * @param member the link to a field as a member of its top-level owner, or null + */ + static JsonObject build(MetaData root, + Function> children, + Function node, + BiFunction member) { + return new Run(children, node, member).build(root); + } + + private static final class Run { + final Function> kids; + final Function node; + final BiFunction member; + + Run(Function> kids, Function node, + BiFunction member) { + this.kids = kids; + this.node = node; + this.member = member; + } + + // ---- model reads ------------------------------------------------------------- + + List fieldsOf(MetaObject obj) { + List out = new ArrayList<>(); + for (MetaData c : kids.apply(obj)) if (c instanceof MetaField f) out.add(f); + return out; + } + + static String description(MetaData md) { + if (!md.hasMetaAttr(DocumentationConstants.DOC_ATTR_DESCRIPTION)) return ""; + Object v = md.getMetaAttr(DocumentationConstants.DOC_ATTR_DESCRIPTION).getValue(); + return v instanceof String s ? s : ""; + } + + static String schemaOf(MetaSource source) { + String s = source.getSchema(); + return s == null ? "" : s; + } + + static boolean isRequired(MetaData field) { + // ADR-0039: resolving, since @required and validator.required may be inherited via extends. + if (field.hasMetaAttr(MetaField.ATTR_REQUIRED) + && Boolean.TRUE.equals(field.getMetaAttr(MetaField.ATTR_REQUIRED).getValue())) return true; + for (MetaData c : field.getChildren(MetaData.class, true)) { + if (MetaValidator.TYPE_VALIDATOR.equals(c.getType()) + && RequiredValidator.SUBTYPE_REQUIRED.equals(c.getSubType())) return true; + } + return false; + } + + static boolean isDerived(MetaData field) { + // ADR-0039 own (category 4): origin.* never inherits (ADR-0029). + return !field.getChildren(MetaOrigin.class, false).isEmpty(); + } + + static boolean isAbstract(MetaData md) { + return DocsView.isAbstract(md); + } + + static boolean hasAttr(MetaData md, String name) { + return md.hasMetaAttr(name); + } + + /** The {@code @discriminator}-bearing ANCESTOR of {@code entity}, or null. */ + static MetaData discriminatorBase(MetaData entity) { + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + for (MetaData a = entity.hasSuperData() ? entity.getSuperData() : null; + a != null && seen.add(a); a = a.hasSuperData() ? a.getSuperData() : null) { + // ADR-0039 sanctioned own: an explicit super-resolution walk reads each ancestor's own attr. + if (a.hasMetaAttr(MetaObject.ATTR_DISCRIMINATOR, false)) return a; + } + return null; + } + + static boolean isTphSubtype(MetaData entity) { + return hasAttr(entity, MetaObject.ATTR_DISCRIMINATOR_VALUE) && discriminatorBase(entity) != null; + } + + static List tphConcreteSubtypes(MetaObject base, List objects) { + List out = new ArrayList<>(); + if (!hasAttr(base, MetaObject.ATTR_DISCRIMINATOR)) return out; + for (MetaObject o : objects) { + if (!isAbstract(o) && hasAttr(o, MetaObject.ATTR_DISCRIMINATOR_VALUE) && discriminatorBase(o) == base) out.add(o); + } + return out; + } + + static List identityFields(MetaIdentity identity) { + List out = new ArrayList<>(); + for (String s : identity.getFields()) { + String t = s.trim(); + if (!t.isEmpty()) out.add(t); + } + return out; + } + + static String columnOf(MetaObject obj, String name) { + MetaField f = obj.findMetaField(name).orElse(null); + return f != null ? ColumnNaming.resolve(f) : ColumnNaming.apply(name, PhysicalNaming.of(obj).columns()); + } + + static boolean isFlattened(MetaField field) { + return ObjectField.SUBTYPE_OBJECT.equals(field.getSubType()) + && hasAttr(field, MetaField.ATTR_STORAGE) + && ObjectField.STORAGE_FLATTENED.equals(field.getMetaAttr(MetaField.ATTR_STORAGE).getValue()); + } + + static RawColumn rawColumn(MetaData field, boolean isPk, String generation, String name) { + String identity = isPk && (MetaIdentity.GENERATION_INCREMENT.equals(generation) + || MetaIdentity.GENERATION_UUID.equals(generation)) ? generation : ""; + return new RawColumn(name, !isPk && !isRequired(field), identity, description(field)); + } + + List fieldColumns(MetaField field, boolean isPk, String generation) { + if (isFlattened(field)) { + MetaObject target = References.refTarget(field, MetaField.ATTR_OBJECT_REF); + List out = new ArrayList<>(); + if (target == null) return out; + for (MetaField nested : fieldsOf(target)) { + out.add(rawColumn(nested, false, "", ColumnNaming.resolveFlattened(field, nested))); + } + return out; + } + return List.of(rawColumn(field, isPk, generation, ColumnNaming.resolve(field))); + } + + /** The referenced key's columns: an explicit dotted tail on {@code @references}, else the + * target's primary identity (its first field), else {@code id}. */ + static List targetColumns(MetaData ref, MetaObject target) { + String tail = ""; + if (ref.hasMetaAttr(ReferenceIdentity.ATTR_REFERENCES)) { + Object raw = ref.getMetaAttr(ReferenceIdentity.ATTR_REFERENCES).getValue(); + if (raw instanceof String s) tail = References.splitChildTail(s).tail(); + } + List names = new ArrayList<>(); + for (String s : (tail.startsWith(".") ? tail.substring(1) : tail).split(",")) { + String t = s.trim(); + if (!t.isEmpty()) names.add(t); + } + if (names.isEmpty()) { + MetaIdentity identity = target.getPrimaryIdentity(); + List pk = identity != null ? identityFields(identity) : List.of(); + names = List.of(pk.isEmpty() ? "id" : pk.get(0)); + } + List out = new ArrayList<>(); + for (String n : names) out.add(columnOf(target, n)); + return out; + } + + static boolean isRef(MetaData c) { + return MetaIdentity.TYPE_IDENTITY.equals(c.getType()) && ReferenceIdentity.SUBTYPE_REFERENCE.equals(c.getSubType()); + } + + JsonArray foreignKeys(MetaObject entity, List objects, Map tableOf) { + List> refs = new ArrayList<>(); + for (MetaData c : entity.getChildren(MetaData.class, true)) if (isRef(c)) refs.add(Map.entry(entity, c)); + if (hasAttr(entity, MetaObject.ATTR_DISCRIMINATOR)) { + Set baseNames = new HashSet<>(); + for (Map.Entry e : refs) baseNames.add(e.getValue().getName()); + for (MetaObject sub : tphConcreteSubtypes(entity, objects)) { + for (MetaData c : sub.getChildren(MetaData.class, true)) { + if (isRef(c) && !baseNames.contains(c.getName())) refs.add(Map.entry(sub, c)); + } + } + } + JsonArray fks = new JsonArray(); + Set seen = new HashSet<>(); + for (Map.Entry e : refs) { + MetaObject holder = e.getKey(); + MetaData ref = e.getValue(); + // A logical-only reference is no constraint. + if (ref.hasMetaAttr(ReferenceIdentity.ATTR_ENFORCE) + && Boolean.FALSE.equals(ref.getMetaAttr(ReferenceIdentity.ATTR_ENFORCE).getValue())) continue; + MetaObject target = References.refTarget(ref, ReferenceIdentity.ATTR_REFERENCES); + if (target == null) continue; + String refTable = tableOf.get(target); + if (refTable == null || refTable.isEmpty()) continue; + List names = identityFields((MetaIdentity) ref); + if (names.isEmpty()) continue; + List columns = new ArrayList<>(); + for (String n : names) columns.add(columnOf(holder, n)); + List refColumns = targetColumns(ref, target); + // Two subtypes may declare the same column: one constraint. + String sig = refTable + "\0" + String.join("\0", columns) + "\1" + String.join("\0", refColumns); + if (!seen.add(sig)) continue; + JsonObject fk = new JsonObject(); + fk.add("columns", strings(columns)); + fk.addProperty("refTable", refTable); + fk.add("refColumns", strings(refColumns)); + fk.add("name", JsonNull.INSTANCE); + fk.add("onDelete", JsonNull.INSTANCE); + fk.add("onUpdate", JsonNull.INSTANCE); + fks.add(fk); + } + return fks; + } + + static String key(String name, String schema) { + return schema.isEmpty() ? name : schema + "." + name; + } + + static JsonArray strings(List items) { + JsonArray a = new JsonArray(); + for (String s : items) a.add(s); + return a; + } + + // ---- the section ------------------------------------------------------------- + + JsonObject build(MetaData root) { + List objects = new ArrayList<>(); + for (MetaData c : kids.apply(root)) if (c instanceof MetaObject o) objects.add(o); + + // Pass 1: which objects own a table, and which are only a foreign-key target. + List> entities = new ArrayList<>(); + List> targetOnly = new ArrayList<>(); + List> tphMembers = new ArrayList<>(); + for (MetaObject obj : objects) { + MetaData base = discriminatorBase(obj); + if (base != null && (isAbstract(obj) || isTphSubtype(obj))) { + tphMembers.add(Map.entry(obj, base)); + continue; + } + if (isAbstract(obj)) continue; + boolean writable = false; + for (MetaSource s : obj.getSources(true)) if (s.isWritable()) writable = true; + if (!writable) continue; + MetaSource source = SourceResolution.primaryRdbSource(obj); + if (source == null) continue; + // ADR-0039 sanctioned own: @unmanaged is read off the object's OWN writable source. + MetaSource own = null; + for (MetaSource s : obj.getSources(false)) { + if (s.isWritable()) { own = s; break; } + } + if (own != null && own.isUnmanaged()) { + targetOnly.add(Map.entry(obj, source)); + continue; + } + entities.add(Map.entry(obj, source)); + } + Map tableOf = new IdentityHashMap<>(); + for (Map.Entry e : entities) tableOf.put(e.getKey(), e.getValue().getPhysicalName()); + for (Map.Entry e : targetOnly) tableOf.put(e.getKey(), e.getValue().getPhysicalName()); + for (Map.Entry m : tphMembers) { + String name = tableOf.get(m.getValue()); + if (name != null && !tableOf.containsKey(m.getKey())) tableOf.put(m.getKey(), name); + } + + // Every object at each storage key, in declaration order. + Map> atKey = new LinkedHashMap<>(); + for (MetaObject obj : objects) { + MetaSource source = SourceResolution.primaryRdbSource(obj); + if (source == null) continue; + atKey.computeIfAbsent(key(source.getPhysicalName(), schemaOf(source)), k -> new ArrayList<>()).add(obj); + } + + List tables = new ArrayList<>(); + Set keys = new HashSet<>(); + for (Map.Entry e : entities) { + MetaObject entity = e.getKey(); + MetaSource source = e.getValue(); + MetaIdentity identity = entity.getPrimaryIdentity(); + List pkNames = identity != null ? identityFields(identity) : List.of(); + String generation = ""; + if (identity != null && identity.hasMetaAttr(MetaIdentity.ATTR_GENERATION) + && identity.getMetaAttr(MetaIdentity.ATTR_GENERATION).getValue() instanceof String g) generation = g; + List raw = new ArrayList<>(); + for (MetaField field : fieldsOf(entity)) { + if (isDerived(field)) continue; + boolean isPk = pkNames.contains(field.getName()); + raw.addAll(fieldColumns(field, isPk, isPk ? generation : "")); + } + if (hasAttr(entity, MetaObject.ATTR_DISCRIMINATOR)) { + Set existing = new HashSet<>(); + for (RawColumn c : raw) existing.add(c.name()); + Set baseFields = new HashSet<>(); + for (MetaField f : fieldsOf(entity)) baseFields.add(f.getName()); + for (MetaObject sub : tphConcreteSubtypes(entity, objects)) { + for (MetaField field : fieldsOf(sub)) { + if (baseFields.contains(field.getName()) || isDerived(field)) continue; + RawColumn col = rawColumn(field, false, "", ColumnNaming.resolve(field)); + if (existing.contains(col.name())) continue; + // A row of any other subtype stores NULL here. + raw.add(col.withNullable(true)); + existing.add(col.name()); + } + } + } + String schema = schemaOf(source); + String k = key(source.getPhysicalName(), schema); + Map mapping = fieldMap(atKey.get(k)); + JsonArray columns = new JsonArray(); + for (RawColumn c : raw) { + Mapped m = mapping.get(c.name()); + JsonObject col = new JsonObject(); + col.addProperty("name", c.name()); + col.add("field", m == null ? JsonNull.INSTANCE : orNull(member.apply(m.owner(), m.field()))); + col.addProperty("nullable", c.nullable()); + col.addProperty("identity", c.identity()); + col.addProperty("description", c.description()); + col.add("sqlType", JsonNull.INSTANCE); + col.add("default", JsonNull.INSTANCE); + columns.add(col); + } + List pk = new ArrayList<>(); + for (String n : pkNames) pk.add(columnOf(entity, n)); + JsonObject table = new JsonObject(); + table.addProperty("name", source.getPhysicalName()); + table.addProperty("schema", schema); + table.add("declaredBy", node.apply(entity)); + table.add("objects", concreteLinks(atKey.get(k))); + table.addProperty("description", description(entity)); + table.add("primaryKey", strings(pk)); + table.add("columns", columns); + table.add("foreignKeys", foreignKeys(entity, objects, tableOf)); + table.add("indexes", JsonNull.INSTANCE); + table.add("checks", JsonNull.INSTANCE); + tables.add(table); + keys.add(k); + } + + List views = new ArrayList<>(); + for (MetaObject obj : objects) { + if (isAbstract(obj)) continue; + MetaSource source = SourceResolution.primaryRdbSource(obj); + if (source == null || !MetaSource.KIND_VIEW.equals(source.getEffectiveKind())) continue; + String schema = schemaOf(source); + String k = key(source.getPhysicalName(), schema); + if (!keys.add(k)) continue; + JsonArray columns = new JsonArray(); + for (Map.Entry c : fieldMap(atKey.get(k)).entrySet()) { + JsonObject col = new JsonObject(); + col.addProperty("name", c.getKey()); + col.add("field", orNull(member.apply(c.getValue().owner(), c.getValue().field()))); + columns.add(col); + } + JsonObject view = new JsonObject(); + view.addProperty("name", source.getPhysicalName()); + view.addProperty("schema", schema); + view.add("declaredBy", node.apply(obj)); + view.add("objects", concreteLinks(atKey.get(k))); + view.add("columns", columns); + views.add(view); + } + + tables.sort((a, b) -> a.get("name").getAsString().compareTo(b.get("name").getAsString())); + views.sort((a, b) -> a.get("name").getAsString().compareTo(b.get("name").getAsString())); + JsonObject storage = new JsonObject(); + storage.addProperty("physical", false); + storage.addProperty("dialect", ""); + storage.add("tables", array(tables)); + storage.add("views", array(views)); + return storage; + } + + /** The column to declaring field map of a storage key (first writer wins on a shared table). */ + Map fieldMap(List atKey) { + Map map = new LinkedHashMap<>(); + if (atKey == null) return map; + for (MetaObject obj : atKey) { + for (MetaField field : fieldsOf(obj)) { + map.putIfAbsent(ColumnNaming.resolve(field), new Mapped(obj, field)); + } + } + return map; + } + + JsonArray concreteLinks(List atKey) { + JsonArray out = new JsonArray(); + if (atKey != null) for (MetaObject o : atKey) if (!isAbstract(o)) out.add(node.apply(o)); + return out; + } + + static JsonElement orNull(JsonObject o) { + return o == null ? JsonNull.INSTANCE : o; + } + + static JsonArray array(List items) { + JsonArray a = new JsonArray(); + for (JsonObject o : items) a.add(o); + return a; + } + } +} From 82c3631e2412f2435cbe0c1331794d69f1a7b5c6 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 07:28:46 -0500 Subject: [PATCH 09/21] wip: Python docs view storage, agent pages from the view, always-on pointer --- .../metaobjects/agent_context/agent_docs.py | 11 + .../metaobjects/agent_context/agent_pages.py | 77 +++ .../metaobjects/codegen/generator_registry.py | 4 +- .../generators/agent_docs_generator.py | 10 +- .../generators/requirements_generator.py | 26 +- .../codegen/runtime/docs_requirements.py | 127 ++-- .../codegen/runtime/docs_schema.py | 652 ++++++------------ server/python/src/metaobjects/docs_view.py | 9 + .../src/metaobjects/docs_view_storage.py | 327 +++++++++ .../tests/codegen/test_docs_site_generator.py | 8 +- .../conformance/test_docs_page_conformance.py | 58 +- server/python/tests/unit/test_agent_docs.py | 34 + 12 files changed, 766 insertions(+), 577 deletions(-) create mode 100644 server/python/src/metaobjects/agent_context/agent_pages.py create mode 100644 server/python/src/metaobjects/docs_view_storage.py diff --git a/server/python/src/metaobjects/agent_context/agent_docs.py b/server/python/src/metaobjects/agent_context/agent_docs.py index 7551c11ad8..36f9b80752 100644 --- a/server/python/src/metaobjects/agent_context/agent_docs.py +++ b/server/python/src/metaobjects/agent_context/agent_docs.py @@ -14,6 +14,12 @@ from metaobjects.config.neutral_config import chose_migrate_dialect +from .agent_pages import ( + ALWAYS_ON_PATH, + render_agent_pages_section, + wired_agent_pages, + with_agent_pages_section, +) from .scaffold import ( AGENT_CONTEXT_MANIFEST_PATH, Manifest, @@ -123,6 +129,11 @@ def run_agent_docs( # Read from the project config on every run, as TypeScript does at init and refresh. migration = chose_migrate_dialect(out) assembled = materialize(tree, servers, clients, docs_ref_for_version(version), migration) + if ALWAYS_ON_PATH in assembled: + # The always-on file points at the agent pages only when the project's last `gen` wrote one. + template = (tree.root / "files" / str(tree.manifest["agentPagesTemplate"])).read_text(encoding="utf-8") + section = render_agent_pages_section(template, wired_agent_pages(out)) + assembled[ALWAYS_ON_PATH] = with_agent_pages_section(assembled[ALWAYS_ON_PATH], section) decision = plan_scaffold( assembled=assembled, prior=prior, diff --git a/server/python/src/metaobjects/agent_context/agent_pages.py b/server/python/src/metaobjects/agent_context/agent_pages.py new file mode 100644 index 0000000000..a7ee816384 --- /dev/null +++ b/server/python/src/metaobjects/agent_context/agent_pages.py @@ -0,0 +1,77 @@ +"""The always-on file's pointer at the pages ``metaobjects gen`` writes for a coding agent. + +The Python side of TypeScript's ``agent-pages.ts``; ``fixtures/agent-pages-pointer/`` pins both. +The pointer is there only when the pages are: what is wired is read off the committed +``.metaobjects/.gen-state/.hashes/`` (one file per package, keyed by the project-relative path of +every file a run wrote), so a project that wires no agent-pages generator is never told to read a +file that does not exist. The section's template is the stored file the shipped manifest names +(``agentPagesTemplate``). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +#: The file the section is inserted into, relative to the project root. +ALWAYS_ON_PATH = ".metaobjects/AGENTS.md" +#: The heading the section is inserted above: the always-on file's rules. +AGENT_PAGES_ANCHOR = "\n## Rules\n" + +#: Each agent page, by the path it ends with, and when to read it. In the order they are listed. +AGENT_PAGES: tuple[tuple[str, str], ...] = ( + ("agent/schema.md", "before you touch persistence: tables, columns, keys and views"), + ("agent/ui.md", "before you touch a form or a grid"), + ("agent/requirements.md", "before you add or change a capability"), + ("AGENT-API.md", "before you call or change the generated API"), + ("requirements.toon", "the requirement ledger, in the form a tool reads"), +) + +_HASHES_DIR = Path(".metaobjects") / ".gen-state" / ".hashes" + + +def _page_index(path: str) -> int: + for i, (suffix, _when) in enumerate(AGENT_PAGES): + if path == suffix or path.endswith("/" + suffix): + return i + return -1 + + +def wired_agent_pages(root: Path) -> list[str]: + """The agent pages the project's last ``gen`` wrote, as project-relative paths, in page + order and then by path. Empty when nothing records one.""" + directory = root / _HASHES_DIR + if not directory.is_dir(): + return [] + found: set[str] = set() + for entry in sorted(directory.iterdir(), key=lambda p: p.name): + if not entry.name.endswith(".json"): + continue + try: + parsed = json.loads(entry.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue # an unreadable hashes file is `gen`'s to report, not this pointer's + if isinstance(parsed, dict): + found.update(path for path in parsed if _page_index(path) >= 0) + return sorted(found, key=lambda p: (_page_index(p), p.encode("utf-16-be"))) + + +def render_agent_pages_section(template: str, pages: list[str]) -> str: + """The section for *pages*, from *template*; ``""`` when there are none.""" + if not pages: + return "" + lines = "\n".join(f"- `{p}`: {AGENT_PAGES[_page_index(p)][1]}." for p in pages) + return template.replace("{{pageList}}", lines) + + +def with_agent_pages_section(always_on: str, section: str) -> str: + """*always_on* with *section* inserted above its rules; unchanged for an empty section.""" + if section == "": + return always_on + at = always_on.find(AGENT_PAGES_ANCHOR) + if at < 0: + raise ValueError( + f'agent-context: the always-on file has no "{AGENT_PAGES_ANCHOR.strip()}" heading ' + "to place the agent pages above" + ) + return always_on[: at + 1] + section + always_on[at + 1 :] diff --git a/server/python/src/metaobjects/codegen/generator_registry.py b/server/python/src/metaobjects/codegen/generator_registry.py index ef5fdb6a95..0cde31d118 100644 --- a/server/python/src/metaobjects/codegen/generator_registry.py +++ b/server/python/src/metaobjects/codegen/generator_registry.py @@ -527,8 +527,8 @@ def _render_helper_default(ctx: GeneratorBuildContext) -> Generator: "requirements": GeneratorEntry( name="requirements", description=( - "The requirement ledger as documentation: requirements.md for people and " - "requirements.toon for tools (shared Mustache templates). No requirement.* node, no file." + "The requirement ledger as requirements.toon, for tools (a shared Mustache template over " + "the docs view); people read it in the explorer (docs-site). No requirement.* node, no file." ), tier="neutral", layer="docs", diff --git a/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py b/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py index 327b6e4999..3e2fdc4aa1 100644 --- a/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py +++ b/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py @@ -9,7 +9,7 @@ Each page is a shared Mustache template (``templates/agent/`` and ``templates/requirements/``, bundled with the package) fed the data the builders in ``codegen/runtime/docs_requirements.py`` -and ``codegen/runtime/docs_schema.py`` compute from the loaded model, pinned by +and ``codegen/runtime/docs_schema.py`` read off the docs view, pinned by ``fixtures/docs-page-conformance/``. A page with nothing to describe is no file. A project overrides a page by dropping a same-named template under its templates directory. """ @@ -19,6 +19,7 @@ from metaobjects.codegen.generator import EmittedFile, GenContext, Generator from metaobjects.config.neutral_config import chose_migrate_dialect +from metaobjects.docs_view import build_docs_view from metaobjects.render.doc_pages import doc_provider, end_with_one_newline, render_doc_page from metaobjects.render.verify import Provider @@ -30,7 +31,6 @@ from ..runtime.docs_schema import ( AGENT_SCHEMA_PAGE_REF, agent_schema_page_data, - schema_rows, ) DEFAULT_AGENT_DIR = "agent" @@ -54,12 +54,12 @@ def __init__( def generate(self, ctx: GenContext) -> list[EmittedFile]: if ctx.loaded_root is None: return [] - root = ctx.loaded_root + view = build_docs_view(ctx.loaded_root) files: list[EmittedFile] = [] # `.metaobjects/config.json` is already part of the run's skip key (cli `_skip_identity`). has_migrate = chose_migrate_dialect(ctx.config.project_root) - schema_data = agent_schema_page_data(root, schema_rows(root), has_migrate) + schema_data = agent_schema_page_data(view, has_migrate) if schema_data is not None: path = f"{self._dir}/schema.md" page = render_doc_page(AGENT_SCHEMA_PAGE_REF, schema_data, self._provider, path) @@ -68,7 +68,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: def render_ledger(data: dict[str, Any]) -> str: return render_doc_page(REQUIREMENTS_PAGE_REF, data, self._provider, "requirements.md") - requirements = agent_requirements_page_data(root, ctx.in_ledger, render_ledger) + requirements = agent_requirements_page_data(view, ctx.in_ledger, render_ledger) if requirements is not None: path = f"{self._dir}/requirements.md" files.append( diff --git a/server/python/src/metaobjects/codegen/generators/requirements_generator.py b/server/python/src/metaobjects/codegen/generators/requirements_generator.py index 9275af91cc..2645860da5 100644 --- a/server/python/src/metaobjects/codegen/generators/requirements_generator.py +++ b/server/python/src/metaobjects/codegen/generators/requirements_generator.py @@ -1,37 +1,35 @@ -"""``requirements`` — the requirement ledger as documentation: ``requirements.md`` for people and -``requirements.toon`` for tools. +"""``requirements`` — the requirement ledger as ``requirements.toon``, for tools. People read it in +the explorer (``docs-site``); the human ``requirements.md`` page is retired. An ordinary entry in a target's ``generators`` (the ``docs`` target by convention), run by ``metaobjects gen``. A model declaring no ``requirement.*`` node gets no file. Each page is the shared Mustache template (``templates/requirements/``, bundled with the -package) fed the data the builder in ``codegen/runtime/docs_requirements.py`` computes; the -rows and the data are pinned by ``fixtures/docs-page-conformance/``. A project overrides a page -by dropping a same-named template under its templates directory. The generator reads the loaded -model and nothing else. +package) fed the data the builder in ``codegen/runtime/docs_requirements.py`` reads off the docs +view; the rows and the data are pinned by ``fixtures/docs-page-conformance/``. A project overrides +a page by dropping a same-named template under its templates directory. The generator reads the +loaded model and nothing else. """ from __future__ import annotations from typing import Any from metaobjects.codegen.generator import EmittedFile, GenContext, Generator +from metaobjects.docs_view import build_docs_view from metaobjects.render.doc_pages import doc_provider, render_doc_page from metaobjects.render.verify import Provider from ..runtime.docs_requirements import ( - REQUIREMENTS_PAGE_REF, REQUIREMENTS_TOON_REF, requirement_rows, - requirements_ledger_data, requirements_toon_data, ) -MARKDOWN_FILENAME = "requirements.md" TOON_FILENAME = "requirements.toon" class RequirementsGenerator: - """Writes ``requirements.md`` and ``requirements.toon`` for the run's loaded model.""" + """Writes ``requirements.toon`` for the run's loaded model.""" name = "requirements" @@ -43,16 +41,10 @@ def __init__(self, template_root: str | None = None, provider: Provider | None = def generate(self, ctx: GenContext) -> list[EmittedFile]: if ctx.loaded_root is None: return [] - rows = requirement_rows(ctx.loaded_root, ctx.in_ledger) + rows = requirement_rows(build_docs_view(ctx.loaded_root), ctx.in_ledger) if not rows: return [] return [ - EmittedFile( - path=MARKDOWN_FILENAME, - content=render_doc_page( - REQUIREMENTS_PAGE_REF, requirements_ledger_data(rows), self._provider, MARKDOWN_FILENAME - ), - ), EmittedFile( path=TOON_FILENAME, content=render_doc_page( diff --git a/server/python/src/metaobjects/codegen/runtime/docs_requirements.py b/server/python/src/metaobjects/codegen/runtime/docs_requirements.py index 9720ad4573..ea24cdecc4 100644 --- a/server/python/src/metaobjects/codegen/runtime/docs_requirements.py +++ b/server/python/src/metaobjects/codegen/runtime/docs_requirements.py @@ -1,8 +1,9 @@ -"""The requirements pages' builders: the ledger rows and the page data of ``requirements.md``, -``requirements.toon`` and ``agent/requirements.md``. +"""The requirements pages' builders: the ledger rows and the page data of ``requirements.toon`` +and ``agent/requirements.md`` (with its embedded ledger), all read off the docs view. -Mirrors the TypeScript ``requirements-view.ts``, ``requirements-markdown.ts``, -``requirements-toon.ts`` and ``agent-requirements-page.ts``. Every page is a shared Mustache +Mirrors the TypeScript ``docs-view-pages.ts``, ``requirements-markdown.ts``, +``requirements-toon.ts`` and ``agent-requirements-page.ts``. The human ``requirements.md`` page is +retired: its template renders only as the ledger embedded in ``agent/requirements.md``. Every page is a shared Mustache template (``templates/requirements/`` and ``templates/agent/``) fed the data built here; the builder makes every decision (heading depth, which title survives, the fact bar, the demotion of the embedded ledger, every table cell, TOON quoting) and the template only lays @@ -19,13 +20,6 @@ import re from typing import Any, Callable -from metaobjects.codegen.requirement_walk import walk_requirements -from metaobjects.documentation.doc_constants import DOC_ATTR_DESCRIPTION, DOC_ATTR_TITLE -from metaobjects.meta.core.requirement.requirement_constants import ( - REQUIREMENT_ATTR_COUNTEREXAMPLE, - REQUIREMENT_ATTR_STATEMENT, -) -from metaobjects.meta.meta_data import MetaData #: The shared template refs (``/``, resolved by a provider). REQUIREMENTS_PAGE_REF = "requirements/requirements.md" @@ -42,44 +36,37 @@ # --- rows ----------------------------------------------------------------------------- -def _string_attr(node: MetaData, name: str) -> str | None: - """A resolving string attr; "declared but empty" is absent.""" - raw = node.get_meta_attr(name) - return raw if isinstance(raw, str) and raw != "" else None +def _opt(text: Any) -> str | None: + """A view string as a row value: "" is absent.""" + return text if isinstance(text, str) and text != "" else None def requirement_rows( - root: MetaData, in_ledger: Callable[[str], bool] | None = None + view: dict[str, Any], in_ledger: Callable[[str], bool] | None = None ) -> list[dict[str, Any]]: - """Every ``requirement.*`` node in the project's ledger, nested ones included, as render-ready - rows in declaration order. Projects over :func:`walk_requirements`, never re-walks. ``[]`` for a - model declaring none, which is what lets the surface write nothing.""" + """Every requirement of the docs view in the project's ledger, nested ones included, as + render-ready rows in document order. ``in_ledger`` is the collection's ledger predicate: a + dependency's requirement the project did not inherit is left out. ``[]`` for a model declaring + none, which is what lets the surface write nothing.""" rows: list[dict[str, Any]] = [] - for walked in walk_requirements(root, in_ledger): - node, view = walked.node, walked.view - row: dict[str, Any] = {"path": view.path, "depth": view.path.count(".")} - title = _string_attr(node, DOC_ATTR_TITLE) - if title is not None: - row["title"] = title - row["subType"] = view.sub_type - if view.level is not None: - row["level"] = view.level - if view.status is not None: - row["status"] = view.status - disposition = node.disposition() - if disposition is not None: - row["disposition"] = disposition - row["trackedBy"] = list(node.tracked_by()) - for key, attr in ( - ("statement", REQUIREMENT_ATTR_STATEMENT), - ("counterexample", REQUIREMENT_ATTR_COUNTEREXAMPLE), - ("description", DOC_ATTR_DESCRIPTION), - ): - value = _string_attr(node, attr) - if value is not None: - row[key] = value - row["implementedBy"] = list(node.implemented_by()) - row["claimedConcerns"] = list(dict.fromkeys(t.concern for t in walked.targets)) + for r in view["requirements"]: + if in_ledger is not None and not in_ledger(r["qualifiedPath"]): + continue + row: dict[str, Any] = {"path": r["address"], "depth": r["depth"]} + if _opt(r["title"]) is not None: + row["title"] = r["title"] + row["subType"] = r["subType"] + if r["level"] is not None: + row["level"] = r["level"] + for key in ("status", "disposition"): + if _opt(r[key]) is not None: + row[key] = r[key] + row["trackedBy"] = list(r["trackedBy"]) + for key in ("statement", "counterexample", "description"): + if _opt(r[key]) is not None: + row[key] = r[key] + row["implementedBy"] = [lk["ref"] for lk in r["implementedBy"]] + row["claimedConcerns"] = list(dict.fromkeys(lk["target"]["kind"] for lk in r["implementedBy"] if lk["resolves"])) rows.append(row) return rows @@ -225,43 +212,33 @@ def requirements_toon_data(rows: list[dict[str, Any]]) -> dict[str, Any]: # --- agent/requirements.md ------------------------------------------------------------ -def _node_address(node: MetaData) -> str: - """The ROOT-level node's resolution key, then the child-name path down to *node*. A claimed - field has a bare name, so the owner is part of the address.""" - segments: list[str] = [] - cur: MetaData | None = node - while cur is not None: - parent = cur.parent - if parent is None or parent.parent is None: - segments.append(cur.resolution_key()) - break - segments.append(cur.name) - cur = parent - return ".".join(reversed(segments)) - - def build_node_index( - root: MetaData, in_ledger: Callable[[str], bool] | None = None + view: dict[str, Any], in_ledger: Callable[[str], bool] | None = None ) -> list[dict[str, Any]]: - """Invert the walk: claimed node -> the requirements that claim it, sorted by address.""" + """Invert the view's resolved ``implementedBy``: claimed node -> the requirements that claim + it, sorted by the node's id. A claim that does not resolve is left out (``meta verify`` + reports it).""" by_address: dict[str, dict[str, Any]] = {} - for walked in walk_requirements(root, in_ledger): - statement = walked.node.get_meta_attr(REQUIREMENT_ATTR_STATEMENT) - for target in walked.targets: - address = _node_address(target.node) + for r in view["requirements"]: + if in_ledger is not None and not in_ledger(r["qualifiedPath"]): + continue + for link in r["implementedBy"]: + if not link["resolves"]: + continue + target = link["target"] entry = by_address.setdefault( - address, {"address": address, "concern": target.concern, "claims": []} + target["id"], {"address": target["id"], "concern": target["kind"], "claims": []} ) entry["claims"].append( { - "path": walked.view.path, - "subType": walked.view.sub_type, - "level": walked.view.level, - "status": walked.view.status, - "statement": statement if isinstance(statement, str) and statement != "" else None, + "path": r["address"], + "subType": r["subType"], + "level": r["level"], + "status": _opt(r["status"]), + "statement": _opt(r["statement"]), } ) - return sorted(by_address.values(), key=lambda e: e["address"]) + return sorted(by_address.values(), key=lambda e: e["address"].encode("utf-16-be")) def md_cell(text: str) -> str: @@ -274,17 +251,17 @@ def one_line(text: str) -> str: def agent_requirements_page_data( - root: MetaData, + view: dict[str, Any], in_ledger: Callable[[str], bool] | None, render_ledger: Callable[[dict[str, Any]], str], ) -> dict[str, Any] | None: """The data ``agent/requirements.md.mustache`` renders, or ``None`` for a model declaring no requirements (no page). *render_ledger* renders the ``requirements`` template from ledger data, so the embedded ledger is that page's own template and cannot disagree with it.""" - rows = requirement_rows(root, in_ledger) + rows = requirement_rows(view, in_ledger) if not rows: return None - index = build_node_index(root, in_ledger) + index = build_node_index(view, in_ledger) stated: dict[str, dict[str, str]] = {} for entry in index: for c in entry["claims"]: diff --git a/server/python/src/metaobjects/codegen/runtime/docs_schema.py b/server/python/src/metaobjects/codegen/runtime/docs_schema.py index 5657bdf4d3..5983581a74 100644 --- a/server/python/src/metaobjects/codegen/runtime/docs_schema.py +++ b/server/python/src/metaobjects/codegen/runtime/docs_schema.py @@ -1,13 +1,12 @@ -"""The MODEL-ONLY ``agent/schema.md``: the rows layer and the page data, built from the model. +"""The MODEL-ONLY ``agent/schema.md``: the rows layer and the page data, read off the docs view. -Mirrors the TypeScript ``agent-schema-rows.ts`` and ``agent-schema-page.ts`` (the -``physical: false`` page). TypeScript builds its rows from the expected schema; a port -without it builds them from the model with its own naming helpers (design call 17 of -``fixtures/docs-page-conformance/``): a table per concrete object whose primary source is a -writable table (abstract bases, sourceless values and ``@unmanaged`` tables have none; a TPH -subtype shares its base's table and adds its own columns after the base's, nullable), a view -per object whose primary source is a view. The page carries no SQL type, default, index, -check, constraint name or referential action: the model cannot know them. +Mirrors the TypeScript ``docs-view-pages.ts`` (``schemaRowsFromView`` and +``agentSchemaPageDataFromView``, the ``physical: false`` page). The docs view's ``storage`` +section (``metaobjects.docs_view_storage``) holds the tables and views the model declares, +named by this port's own naming helpers (design call 17 of ``fixtures/docs-page-conformance/``); +the relationships and enums are read from the members of the nodes it links. The page carries +no SQL type, default, index, check, constraint name or referential action: the model cannot +know them. Rows and page data are plain dicts so they compare as JSON values against the corpus. """ @@ -16,301 +15,66 @@ import re from typing import Any -from metaobjects.codegen.instance_artifacts import is_abstract -from metaobjects.codegen.model_walk import is_required from .docs_requirements import GENERATED_MARKER -from metaobjects.codegen.type_map import effective_enum_values -from metaobjects.documentation.doc_constants import DOC_ATTR_DESCRIPTION -from metaobjects.meta.core.field import field_constants as fc -from metaobjects.meta.core.field.meta_field import MetaField -from metaobjects.meta.core.identity.identity_constants import ( - GENERATION_INCREMENT, - GENERATION_UUID, - IDENTITY_ATTR_FIELDS, - IDENTITY_ATTR_GENERATION, - IDENTITY_REFERENCE_ATTR_ENFORCE, - IDENTITY_REFERENCE_ATTR_REFERENCES, - IDENTITY_SUBTYPE_REFERENCE, -) -from metaobjects.meta.core.object.meta_object import MetaObject -from metaobjects.meta.core.object.object_constants import ( - OBJECT_ATTR_DISCRIMINATOR, - OBJECT_ATTR_DISCRIMINATOR_VALUE, - OBJECT_SUBTYPE_REPORT, -) -from metaobjects.meta.core.relationship.relationship_constants import ( - CARDINALITY_MANY, - CARDINALITY_ONE, - RELATIONSHIP_ATTR_CARDINALITY, - RELATIONSHIP_ATTR_OBJECT_REF, - RELATIONSHIP_ATTR_ON_DELETE, - RELATIONSHIP_ATTR_THROUGH, -) -from metaobjects.meta.meta_data import MetaData -from metaobjects.meta.persistence.origin import origin_constants as oc -from metaobjects.meta.persistence.source.meta_source import MetaSource -from metaobjects.naming import ( - apply_column_naming_strategy, - naming_rules_of, - resolve_column_name, - resolve_flattened_column_name, -) -from metaobjects.naming_refs import ref_target, split_child_tail -from metaobjects.shared.base_types import TYPE_IDENTITY, TYPE_ORIGIN, TYPE_RELATIONSHIP -from metaobjects.source_resolution import primary_rdb_source AGENT_SCHEMA_PAGE_REF = "agent/schema.md" -_SOURCE_KIND_VIEW = "view" +_TYPE_OBJECT = "object" +_TYPE_FIELD = "field" +_TYPE_ORIGIN = "origin" +_TYPE_RELATIONSHIP = "relationship" +_KIND_REPORT = "object.report" +_SUBTYPE_ENUM = "enum" +Json = dict[str, Any] -def is_report(obj: MetaObject) -> bool: - return obj.sub_type == OBJECT_SUBTYPE_REPORT - -# --- the model, as rows --------------------------------------------------------------- - - -def row_key(name: str, schema: str | None) -> str: +def row_key(name: str, schema: str) -> str: """The key ``declaredBy`` uses: what a page heading prints, without the backticks.""" - return name if schema is None else f"{schema}.{name}" - - -def _objects(root: MetaData) -> list[MetaObject]: - return [c for c in root.children() if isinstance(c, MetaObject)] - - -def _description(node: MetaData) -> str | None: - v = node.get_meta_attr(DOC_ATTR_DESCRIPTION) - return v if isinstance(v, str) and v != "" else None - - -def _discriminator_base(entity: MetaData) -> MetaData | None: - """The ``@discriminator``-bearing ANCESTOR of *entity*, or ``None``.""" - ancestor = entity.super_data - while ancestor is not None: - # ADR-0039 sanctioned own: explicit super-resolution walk, each ancestor's own attr. - if ancestor.attr(OBJECT_ATTR_DISCRIMINATOR) is not None: - return ancestor - ancestor = ancestor.super_data - return None - - -def _is_tph_subtype(entity: MetaData) -> bool: - return ( - entity.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR_VALUE) is not None - and _discriminator_base(entity) is not None - ) - - -def _tph_concrete_subtypes(base: MetaObject, objects: list[MetaObject]) -> list[MetaObject]: - if base.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR) is None: - return [] - return [ - o - for o in objects - if not is_abstract(o) - and o.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR_VALUE) is not None - and _discriminator_base(o) is base - ] - - -def _identity_fields(identity: MetaData) -> list[str]: - v = identity.get_meta_attr(IDENTITY_ATTR_FIELDS) - if isinstance(v, str): - return [s.strip() for s in v.split(",") if s.strip()] - return [str(x) for x in v] if isinstance(v, (list, tuple)) else [] - - -def _find_field(obj: MetaObject, name: str) -> MetaField | None: - return obj.find_field(name) - - -def _column_row(field: MetaData, is_pk: bool, generation: str | None, name: str) -> dict[str, Any]: - col: dict[str, Any] = {"name": name, "nullable": not is_pk and not is_required(field)} - if is_pk and generation in (GENERATION_INCREMENT, GENERATION_UUID): - col["identity"] = generation - description = _description(field) - if description is not None: - col["description"] = description - return col - - -def _flattened(field: MetaField) -> bool: - return ( - field.sub_type == fc.FIELD_SUBTYPE_OBJECT - and field.get_meta_attr(fc.FIELD_ATTR_STORAGE) == fc.STORAGE_FLATTENED - ) - - -def _field_columns(field: MetaField, is_pk: bool, generation: str | None) -> list[dict[str, Any]]: - if _flattened(field): - target = ref_target(field, fc.FIELD_ATTR_OBJECT_REF) - if not isinstance(target, MetaObject): - return [] - return [ - _column_row(nested, False, None, resolve_flattened_column_name(field, nested)) - for nested in target.fields() + return name if schema == "" else f"{schema}.{name}" + + +# --- the rows layer, read off the view's storage --------------------------------------- + + +def schema_rows(view: Json) -> Json: + """The rows layer of the model-only schema page: tables and views as the view's storage + lists them (sorted by name), a table's columns and keys in declaration order, and + ``declaredBy`` (each table or view -> the declaring object).""" + storage = view["storage"] + declared: list[tuple[str, str]] = [] + tables: list[Json] = [] + for t in storage["tables"]: + declared.append((row_key(t["name"], t["schema"]), t["declaredBy"]["id"])) + table: Json = {"name": t["name"]} + if t["schema"] != "": + table["schema"] = t["schema"] + if t["description"] != "": + table["description"] = t["description"] + table["primaryKey"] = t["primaryKey"] + table["columns"] = [ + { + "name": c["name"], + "nullable": c["nullable"], + **({"identity": c["identity"]} if c["identity"] != "" else {}), + **({"description": c["description"]} if c["description"] != "" else {}), + } + for c in t["columns"] + ] + table["foreignKeys"] = [ + {"columns": f["columns"], "refTable": f["refTable"], "refColumns": f["refColumns"]} + for f in t["foreignKeys"] ] - return [_column_row(field, is_pk, generation, resolve_column_name(field))] - - -def _target_columns(ref: MetaData, target: MetaObject) -> list[str]: - """The referenced key's columns: an explicit dotted tail on ``@references``, else the - target's primary identity (its first field), else ``id``.""" - raw = ref.get_meta_attr(IDENTITY_REFERENCE_ATTR_REFERENCES) - tail = split_child_tail(raw)[1] if isinstance(raw, str) else "" - explicit = [s.strip() for s in tail.lstrip(".").split(",") if s.strip()] - if explicit: - names = explicit - else: - identity = target.primary_identity() - pk = _identity_fields(identity) if identity is not None else [] - names = [pk[0] if pk else "id"] - out = [] - for name in names: - f = _find_field(target, name) - out.append(resolve_column_name(f) if f is not None else apply_column_naming_strategy(name, naming_rules_of(target).columns)) - return out - - -def _foreign_keys( - entity: MetaObject, objects: list[MetaObject], table_of: dict[str, str] -) -> list[dict[str, Any]]: - refs: list[tuple[MetaObject, MetaData]] = [ - (entity, c) for c in entity.children() if c.type == TYPE_IDENTITY and c.sub_type == IDENTITY_SUBTYPE_REFERENCE - ] - if entity.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR) is not None: - base_names = {r.name for _h, r in refs} - for sub in _tph_concrete_subtypes(entity, objects): - for c in sub.children(): - if c.type == TYPE_IDENTITY and c.sub_type == IDENTITY_SUBTYPE_REFERENCE and c.name not in base_names: - refs.append((sub, c)) - fks: list[dict[str, Any]] = [] - for holder, ref in refs: - if ref.get_meta_attr(IDENTITY_REFERENCE_ATTR_ENFORCE) is False: - continue # a logical-only reference is no constraint - target = ref_target(ref, IDENTITY_REFERENCE_ATTR_REFERENCES) - if not isinstance(target, MetaObject): - continue - ref_table = table_of.get(target.resolution_key()) - if not ref_table: - continue - names = _identity_fields(ref) - if not names: - continue - columns = [] - for name in names: - f = _find_field(holder, name) - columns.append(resolve_column_name(f) if f is not None else apply_column_naming_strategy(name, naming_rules_of(holder).columns)) - fk = {"columns": columns, "refTable": ref_table, "refColumns": _target_columns(ref, target)} - if fk not in fks: # two subtypes may declare the same column: one constraint - fks.append(fk) - return fks - - -def _primary(entity: MetaObject) -> MetaSource | None: - return primary_rdb_source(entity) - - -def schema_rows(root: MetaData) -> dict[str, Any]: - """The rows layer of the model-only schema page: tables and views sorted by name (code - points, as the snapshot file sorts them), a table's columns and keys in declaration order, - and ``declaredBy`` (each table or view -> the declaring object).""" - objects = _objects(root) - # Pass 1: which objects own a table, and which are only an FK target. - entities: list[tuple[MetaObject, MetaSource]] = [] - target_only: list[tuple[MetaObject, MetaSource]] = [] - tph_members: list[tuple[MetaObject, MetaData]] = [] - for obj in objects: - base = _discriminator_base(obj) - if base is not None and (is_abstract(obj) or _is_tph_subtype(obj)): - tph_members.append((obj, base)) - continue - if is_abstract(obj): - continue - if not any(isinstance(c, MetaSource) and c.is_writable() for c in obj.children()): - continue - source = _primary(obj) - if source is None: - continue - # ADR-0039 sanctioned own: @unmanaged is read off the object's OWN writable source. - own = next((c for c in obj.own_children() if isinstance(c, MetaSource) and c.is_writable()), None) - if own is not None and own.is_unmanaged(): - target_only.append((obj, source)) - continue - entities.append((obj, source)) - table_of: dict[str, str] = {o.resolution_key(): s.physical_name() for o, s in [*entities, *target_only]} - for member, base in tph_members: - name = table_of.get(base.resolution_key()) - if name is not None and member.resolution_key() not in table_of: - table_of[member.resolution_key()] = name - - tables: list[dict[str, Any]] = [] - declared: dict[str, str] = {} - for entity, source in entities: - identity = entity.primary_identity() - pk_names = _identity_fields(identity) if identity is not None else [] - generation = identity.get_meta_attr(IDENTITY_ATTR_GENERATION) if identity is not None else None - generation = generation if isinstance(generation, str) else None - primary_key = [] - for name in pk_names: - f = _find_field(entity, name) - primary_key.append(resolve_column_name(f) if f is not None else apply_column_naming_strategy(name, naming_rules_of(entity).columns)) - columns: list[dict[str, Any]] = [] - for field in entity.fields(): - if field.is_derived(): - continue - columns.extend(_field_columns(field, field.name in pk_names, generation if field.name in pk_names else None)) - if entity.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR) is not None: - existing = {c["name"] for c in columns} - base_fields = {f.name for f in entity.fields()} - for sub in _tph_concrete_subtypes(entity, objects): - for field in sub.fields(): - if field.name in base_fields or field.is_derived(): - continue - col = _column_row(field, False, None, resolve_column_name(field)) - if col["name"] in existing: - continue - col["nullable"] = True # a row of any other subtype stores NULL here - columns.append(col) - existing.add(col["name"]) - table: dict[str, Any] = {"name": source.physical_name()} - schema = source.schema() - if schema is not None: - table["schema"] = schema - description = _description(entity) - if description is not None: - table["description"] = description - table["primaryKey"] = primary_key - table["columns"] = columns - table["foreignKeys"] = _foreign_keys(entity, objects, table_of) tables.append(table) - declared[row_key(table["name"], schema)] = entity.resolution_key() - - views: list[dict[str, Any]] = [] - for obj in objects: - if is_abstract(obj): - continue - source = _primary(obj) - if source is None or source.effective_kind() != _SOURCE_KIND_VIEW: - continue - view: dict[str, Any] = {"name": source.physical_name()} - schema = source.schema() - if schema is not None: - view["schema"] = schema - key = row_key(view["name"], schema) - if key in declared: - continue - views.append(view) - declared[key] = obj.resolution_key() - - tables.sort(key=lambda t: t["name"]) - views.sort(key=lambda v: v["name"]) - return {"tables": tables, "views": views, "declaredBy": dict(sorted(declared.items()))} + views: list[Json] = [] + for v in storage["views"]: + declared.append((row_key(v["name"], v["schema"]), v["declaredBy"]["id"])) + views.append({"name": v["name"], **({"schema": v["schema"]} if v["schema"] != "" else {})}) + declared.sort(key=lambda kv: kv[0].encode("utf-16-be")) + return {"tables": tables, "views": views, "declaredBy": dict(declared)} -# --- the page, from rows and the model ------------------------------------------------ +# --- the page, from the view ---------------------------------------------------------- def _md_cell_free(text: str) -> str: @@ -321,169 +85,116 @@ def _cols(names: list[str]) -> str: return "—" if not names else ", ".join(f"`{c}`" for c in names) -def _key_cell(table: dict[str, Any], column: dict[str, Any]) -> str: +def _key_cell(table: Json, column: str) -> str: roles: list[str] = [] - if column["name"] in table["primaryKey"]: + if column in table["primaryKey"]: roles.append("PK (composite)" if len(table["primaryKey"]) > 1 else "PK") - fk = next((f for f in table["foreignKeys"] if column["name"] in f["columns"]), None) + fk = next((f for f in table["foreignKeys"] if column in f["columns"]), None) if fk is not None: roles.append(f"FK → `{fk['refTable']}`") return " · ".join(roles) -def _lineage_of(field: MetaField) -> str | None: - # ADR-0039 sanctioned own: an origin.* NEVER inherits. - origin = next((c for c in field.own_children() if c.type == TYPE_ORIGIN), None) - if origin is None: +def _members_by_id(view: Json) -> dict[str, Json]: + """Every member of every node, by id.""" + out: dict[str, Json] = {} + + def visit(m: Json) -> None: + out[m["id"]] = m + for g in m["memberGroups"]: + for c in g["members"]: + visit(c) + + for n in view["nodes"]: + for g in n["memberGroups"]: + for m in g["members"]: + visit(m) + return out + + +def _direct_members(n: Json, type_: str) -> list[Json]: + return next((g["members"] for g in n["memberGroups"] if g["type"] == type_), []) + + +def _attr_value(attrs: list[Json], name: str) -> Any: + return next((a["value"] for a in attrs if a["name"] == name), None) + + +def _attr_text(attrs: list[Json], name: str) -> str | None: + """A string attribute as a page prints it: a resolved reference by its link's label (what + the author wrote, relative to the model: ``Owner.name``), anything else as its text.""" + a = next((x for x in attrs if x["name"] == name), None) + if a is None or not isinstance(a["value"], str): return None + first = a["values"][0] if a["values"] else None + link = first.get("link") if first is not None else None + text = link["label"] if link is not None and not link["unresolved"] else a["value"] + return None if text == "" else text - def text(name: str) -> str | None: - v = origin.authored_attr(name) - return v if isinstance(v, str) and v != "" else None - - sub = origin.sub_type - if sub == oc.ORIGIN_SUBTYPE_PASSTHROUGH: - src, via = text(oc.ORIGIN_ATTR_FROM), text(oc.ORIGIN_ATTR_VIA) - return f"passthrough from `{src or '?'}`" + ("" if via is None else f" via `{via}`") - if sub == oc.ORIGIN_SUBTYPE_AGGREGATE: - agg = text(oc.ORIGIN_ATTR_AGG) or "?" - of, via = text(oc.ORIGIN_ATTR_OF), text(oc.ORIGIN_ATTR_VIA) - return f"`{agg}`" + ("" if of is None else f" of `{of}`") + ("" if via is None else f" via `{via}`") - if sub == oc.ORIGIN_SUBTYPE_FIRST: - of, via, order = text(oc.ORIGIN_ATTR_OF), text(oc.ORIGIN_ATTR_VIA), text(oc.ORIGIN_ATTR_ORDER_BY) - return ( - "first" - + ("" if of is None else f" `{of}`") - + ("" if via is None else f" via `{via}`") - + ("" if order is None else f" ordered by `{order}`") - ) - if sub == oc.ORIGIN_SUBTYPE_COMPUTED: + +def _lineage_of(field: Json | None) -> str | None: + """The lineage text of a view column, from its field's ``origin.*`` member.""" + origins = [] if field is None else _direct_members(field, _TYPE_ORIGIN) + if not origins: + return None + origin = origins[0] + + def t(name: str) -> str | None: + return _attr_text(origin["attrs"], name) + + sub = origin["subType"] + via = t("via") + via_part = "" if via is None else f" via `{via}`" + if sub == "passthrough": + return f"passthrough from `{t('from') or '?'}`" + via_part + if sub == "aggregate": + of = t("of") + return f"`{t('agg') or '?'}`" + ("" if of is None else f" of `{of}`") + via_part + if sub == "first": + of, order = t("of"), t("orderBy") + return "first" + ("" if of is None else f" `{of}`") + via_part + ("" if order is None else f" ordered by `{order}`") + if sub == "computed": return "computed from a declared `@expr`" return f"`origin.{sub}`" -def _cardinality_phrase(cardinality: object, through: object) -> str: - if cardinality == CARDINALITY_MANY: - return "many-to-many" if isinstance(through, str) and through != "" else "one-to-many" - if cardinality == CARDINALITY_ONE: +def _cardinality_phrase(cardinality: Any, through: str | None) -> str: + if cardinality == "many": + return "many-to-many" if through is not None else "one-to-many" + if cardinality == "one": return "many-to-one" return "cardinality not declared" -def _relationship_lines(objects: list[MetaObject]) -> list[str]: - out: list[str] = [] - for obj in objects: - for rel in (c for c in obj.children() if c.type == TYPE_RELATIONSHIP): - cardinality = rel.get_meta_attr(RELATIONSHIP_ATTR_CARDINALITY) - target = rel.authored_attr(RELATIONSHIP_ATTR_OBJECT_REF) - through = rel.authored_attr(RELATIONSHIP_ATTR_THROUGH) - on_delete = rel.get_meta_attr(RELATIONSHIP_ATTR_ON_DELETE) - parts = [f"`{obj.resolution_key()}.{rel.name}`", f"`{rel.sub_type}`"] - parts.append(f"{_cardinality_phrase(cardinality, through)} → `{target if target is not None else '?'}`") - if isinstance(through, str) and through != "": - parts.append(f"through `{through}`") - if isinstance(on_delete, str) and on_delete != "": - parts.append(f"on delete `{on_delete}`") - out.append(" · ".join(parts)) - return out - - -def _enum_rows(objects: list[MetaObject]) -> list[dict[str, str]]: - rows: list[dict[str, str]] = [] - for obj in objects: - for field in obj.fields(): - if field.sub_type != fc.FIELD_SUBTYPE_ENUM: - continue - members = effective_enum_values(field) - if not members: - continue - int_map = field.get_meta_attr(fc.FIELD_ATTR_INT_VALUE_MAP) - if isinstance(int_map, dict): - storage = "int-backed (" + ", ".join(f"{m}={int_map[m]}" for m in members) + ")" - else: - storage = "string-backed" - rows.append( - { - "field": f"{obj.resolution_key()}.{field.name}", - "members": ", ".join(f"`{m}`" for m in members), - "storage": storage, - } - ) - return rows - - -def agent_schema_page_data( - root: MetaData, rows: dict[str, Any], has_migrate: bool = False -) -> dict[str, Any] | None: - """The data ``agent/schema.md.mustache`` renders (``physical: false``), built from the rows - and the model alone. ``has_migrate``: the project chose a ``meta migrate`` dialect - (``metaobjects.config.neutral_config.chose_migrate_dialect``). ``None`` when there is no table and no view: no page.""" - if not rows["tables"] and not rows["views"]: +def agent_schema_page_data(view: Json, has_migrate: bool = False) -> Json | None: + """The data ``agent/schema.md.mustache`` renders (``physical: false``), built from the docs + view alone. ``has_migrate``: the project chose a ``meta migrate`` dialect + (``metaobjects.config.neutral_config.chose_migrate_dialect``). ``None`` when the model + declares no table and no view: no page.""" + tables, views = view["storage"]["tables"], view["storage"]["views"] + if not tables and not views: return None - objects = _objects(root) - table_keys = {row_key(t["name"], t.get("schema")) for t in rows["tables"]} - view_keys = {row_key(v["name"], v.get("schema")) for v in rows["views"]} - - table_backed: list[MetaObject] = [] - declared_by: dict[str, dict[str, tuple[str, str]]] = {} - view_lineage: dict[str, list[dict[str, str]]] = {} - report_views: set[str] = set() - for obj in objects: - source = _primary(obj) - if source is None: - continue - key = row_key(source.physical_name(), source.schema()) - is_table = key in table_keys - if not is_table and key not in view_keys: - continue - # An abstract base that declares the source its concrete child inherits resolves to - # that child's table: it is in the schema but is no table-backed object. - if is_table and not is_abstract(obj): - table_backed.append(obj) - if not is_table and is_report(obj): - report_views.add(key) - mapping = declared_by.setdefault(key, {}) - lineage: list[dict[str, str]] = [] - for field in obj.fields(): - column = resolve_column_name(field) - # A TPH base and its subtypes share one table: first writer wins. - if column not in mapping: - mapping[column] = (field.name, f"{field.type}.{field.sub_type}") - text = _lineage_of(field) - if text is not None: - lineage.append({"column": column, "text": text}) - if lineage: - view_lineage[key] = lineage - - relationships = _relationship_lines(objects) - enums = _enum_rows(table_backed) - any_description = any( - t.get("description", "") != "" or any(c.get("description", "") != "" for c in t["columns"]) - for t in rows["tables"] - ) - - tables = [] - for table in sorted(rows["tables"], key=lambda t: t["name"]): - key = row_key(table["name"], table.get("schema")) - mapping = declared_by.get(key, {}) - described = [c for c in table["columns"] if c.get("description", "") != ""] - fks = [f"{_cols(f['columns'])} → `{f['refTable']}`({_cols(f['refColumns'])})" for f in table["foreignKeys"]] - entry: dict[str, Any] = {"heading": f"`{key}`"} - if key in rows["declaredBy"]: - entry["tableDeclaredBy"] = rows["declaredBy"][key] - if table.get("description", "") != "": - entry["tableDescription"] = _md_cell_free(table["description"]) + members = _members_by_id(view) + by_order = sorted(view["nodes"], key=lambda n: n["order"]) + + table_data: list[Json] = [] + for t in tables: + described = [c for c in t["columns"] if c["description"] != ""] + fks = [f"{_cols(f['columns'])} → `{f['refTable']}`({_cols(f['refColumns'])})" for f in t["foreignKeys"]] + entry: Json = {"heading": f"`{row_key(t['name'], t['schema'])}`", "tableDeclaredBy": t["declaredBy"]["id"]} + if t["description"] != "": + entry["tableDescription"] = _md_cell_free(t["description"]) entry["columns"] = [ { "name": c["name"], - "fieldCell": f"`{mapping[c['name']][0]}`" if c["name"] in mapping else "", - "declaredCell": f"`{mapping[c['name']][1]}`" if c["name"] in mapping else "", + "fieldCell": "" if c["field"] is None else f"`{members[c['field']['id']]['name']}`", + "declaredCell": "" if c["field"] is None else f"`{c['field']['kind']}`", "sqlTypeCell": "", "nullCell": "yes" if c["nullable"] else "no", "defaultCell": "", - "keyCell": _key_cell(table, c), + "keyCell": _key_cell(t, c["name"]), } - for c in table["columns"] + for c in t["columns"] ] entry.update( hasDescribed=len(described) > 0, @@ -495,30 +206,75 @@ def agent_schema_page_data( hasChecks=False, checks=[], ) - tables.append(entry) - - views = [] - for view in sorted(rows["views"], key=lambda v: v["name"]): - key = row_key(view["name"], view.get("schema")) - lineage = view_lineage.get(key, []) - entry = {"heading": f"`{key}`"} - if key in rows["declaredBy"]: - entry["viewDeclaredBy"] = rows["declaredBy"][key] - entry["hasLineage"] = len(lineage) > 0 - entry["lineage"] = lineage - views.append(entry) + table_data.append(entry) + + view_data: list[Json] = [] + for v in views: + lineage: list[Json] = [] + for c in v["columns"]: + text = _lineage_of(None if c["field"] is None else members.get(c["field"]["id"])) + if text is not None: + lineage.append({"column": c["name"], "text": text}) + view_data.append({ + "heading": f"`{row_key(v['name'], v['schema'])}`", + "viewDeclaredBy": v["declaredBy"]["id"], + "hasLineage": len(lineage) > 0, + "lineage": lineage, + }) + + # Every relationship as written, in declaration order of its object. + relationships: list[str] = [] + for n in by_order: + if n["type"] != _TYPE_OBJECT: + continue + for rel in _direct_members(n, _TYPE_RELATIONSHIP): + through = _attr_text(rel["attrs"], "through") + on_delete = _attr_text(rel["attrs"], "onDelete") + target = _attr_text(rel["attrs"], "objectRef") + parts = [f"`{n['id']}.{rel['name']}`", f"`{rel['subType']}`"] + parts.append(f"{_cardinality_phrase(_attr_value(rel['attrs'], 'cardinality'), through)} → `{target if target is not None else '?'}`") + if through is not None: + parts.append(f"through `{through}`") + if on_delete is not None: + parts.append(f"on delete `{on_delete}`") + relationships.append(" · ".join(parts)) + + # Every enum field of a table-backed object, in declaration order of its object. + table_backed = {o["id"] for t in tables for o in t["objects"]} + enums: list[Json] = [] + for n in by_order: + if n["id"] not in table_backed: + continue + for f in _direct_members(n, _TYPE_FIELD): + if f["subType"] != _SUBTYPE_ENUM: + continue + values = _attr_value(f["attrs"], "values") + names = [str(x) for x in values] if isinstance(values, list) else [] + if not names: + continue + int_map = _attr_value(f["attrs"], "intValueMap") + if isinstance(int_map, dict): + storage = "int-backed (" + ", ".join(f"{m}={int_map.get(m)}" for m in names) + ")" + else: + storage = "string-backed" + enums.append({ + "field": f"{n['id']}.{f['name']}", + "members": ", ".join(f"`{m}`" for m in names), + "storage": storage, + }) + any_description = any(t["description"] != "" or any(c["description"] != "" for c in t["columns"]) for t in tables) return { "generatedMarker": GENERATED_MARKER, "physical": False, "dialect": "", - "descriptionNudge": not any_description and len(rows["tables"]) > 0, + "descriptionNudge": not any_description and len(tables) > 0, "hasMigrate": has_migrate, - "hasTables": len(tables) > 0, - "tables": tables, - "hasViews": len(views) > 0, - "hasReportView": any(row_key(v["name"], v.get("schema")) in report_views for v in rows["views"]), - "views": views, + "hasTables": len(table_data) > 0, + "tables": table_data, + "hasViews": len(view_data) > 0, + "hasReportView": any(o["kind"] == _KIND_REPORT for v in views for o in v["objects"]), + "views": view_data, "hasRelationships": len(relationships) > 0, "relationships": relationships, "hasEnums": len(enums) > 0, diff --git a/server/python/src/metaobjects/docs_view.py b/server/python/src/metaobjects/docs_view.py index f3909fe8f9..2f3c75d4d0 100644 --- a/server/python/src/metaobjects/docs_view.py +++ b/server/python/src/metaobjects/docs_view.py @@ -35,6 +35,7 @@ from .requirement_check import effective_package from .naming_refs import effective_package_of, is_ref_bearing_attr, split_child_tail from .documentation.doc_constants import DOC_ATTR_DESCRIPTION, DOC_ATTR_SUMMARY, DOC_ATTR_TITLE +from .docs_view_storage import build_storage from .serializer_json import _normalize from .shared.base_types import TYPE_FIELD, TYPE_OBJECT, TYPE_REQUIREMENT, TYPE_TEMPLATE from .shared.separators import PACKAGE_SEP @@ -761,9 +762,17 @@ def num(k: str) -> int | float | None: "requirements": requirements, "advisories": advisories, "slices": _slices_of(b, nodes, requirements), + "storage": build_storage(root, lambda md: b.link_to(md, md.name), lambda owner, field: _member_link(b, owner, field)), } +def _member_link(b: _Builder, owner: MetaData, field: MetaData) -> Json | None: + """The link to *field* as a member of the top-level *owner*: its own row of an inherited one.""" + top = b.canonical.get(id(owner)) + row = None if top is None else next((c for c in top.children if c.md is field), None) + return None if row is None else b.link(row) + + def _slices_of(b: _Builder, nodes: list[Json], requirements: list[Json]) -> list[Json]: slices: list[Json] = [] diff --git a/server/python/src/metaobjects/docs_view_storage.py b/server/python/src/metaobjects/docs_view_storage.py new file mode 100644 index 0000000000..eefdd26b75 --- /dev/null +++ b/server/python/src/metaobjects/docs_view_storage.py @@ -0,0 +1,327 @@ +"""The docs view's ``storage`` section: the tables and views the model declares, named by the +port's own naming helpers (``docs/features/docs-view.md``, "storage"). + +The Python port of TypeScript's ``storage.ts`` (``@metaobjectsdev/metadata``), held to the +same bytes by ``fixtures/explorer-conformance/``. MODEL-ONLY: a table per concrete object +whose primary source is a writable, managed table (abstract bases, sourceless values and +``@unmanaged`` tables have none; a TPH subtype shares its base's table and adds its own +columns after the base's, nullable), a view per object whose primary source is a view. The +physical facts (SQL type, default, indexes, checks, constraint names, referential actions) +are ``None`` here and ``physical`` is false: only the TypeScript run fills them. +""" +from __future__ import annotations + +from typing import Any, Callable + +from .codegen.model_walk import is_required +from .documentation.doc_constants import DOC_ATTR_DESCRIPTION +from .meta.core.field import field_constants as fc +from .meta.core.field.meta_field import MetaField +from .meta.core.identity.identity_constants import ( + GENERATION_INCREMENT, + GENERATION_UUID, + IDENTITY_ATTR_FIELDS, + IDENTITY_ATTR_GENERATION, + IDENTITY_REFERENCE_ATTR_ENFORCE, + IDENTITY_REFERENCE_ATTR_REFERENCES, + IDENTITY_SUBTYPE_REFERENCE, +) +from .meta.core.object.meta_object import MetaObject +from .meta.core.object.object_constants import OBJECT_ATTR_DISCRIMINATOR, OBJECT_ATTR_DISCRIMINATOR_VALUE +from .meta.meta_data import MetaData +from .meta.persistence.source.meta_source import MetaSource +from .naming import ( + apply_column_naming_strategy, + naming_rules_of, + resolve_column_name, + resolve_flattened_column_name, +) +from .naming_refs import ref_target, split_child_tail +from .shared.base_types import TYPE_IDENTITY +from .source_resolution import primary_rdb_source + +Json = dict[str, Any] + +_SOURCE_KIND_VIEW = "view" + + +def _cu(s: str) -> bytes: + return s.encode("utf-16-be") + + +def _description(node: MetaData) -> str: + v = node.get_meta_attr(DOC_ATTR_DESCRIPTION) + return v if isinstance(v, str) else "" + + +def _schema_of(source: MetaSource) -> str: + v = source.schema() + return v if isinstance(v, str) else "" + + +def _is_abstract(obj: MetaObject) -> bool: + return obj.is_abstract is True + + +def _discriminator_base(entity: MetaData) -> MetaData | None: + """The ``@discriminator``-bearing ANCESTOR of *entity*, or ``None``.""" + ancestor = entity.super_data + while ancestor is not None: + # ADR-0039 sanctioned own: an explicit super-resolution walk reads each ancestor's own attr. + if ancestor.attr(OBJECT_ATTR_DISCRIMINATOR) is not None: + return ancestor + ancestor = ancestor.super_data + return None + + +def _is_tph_subtype(entity: MetaData) -> bool: + return ( + entity.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR_VALUE) is not None + and _discriminator_base(entity) is not None + ) + + +def _tph_concrete_subtypes(base: MetaObject, objects: list[MetaObject]) -> list[MetaObject]: + if base.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR) is None: + return [] + return [ + o + for o in objects + if not _is_abstract(o) + and o.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR_VALUE) is not None + and _discriminator_base(o) is base + ] + + +def _identity_fields(identity: MetaData) -> list[str]: + v = identity.get_meta_attr(IDENTITY_ATTR_FIELDS) + if isinstance(v, str): + return [s.strip() for s in v.split(",") if s.strip()] + return [str(x) for x in v] if isinstance(v, (list, tuple)) else [] + + +def _column_of(obj: MetaObject, name: str) -> str: + f = obj.find_field(name) + return resolve_column_name(f) if f is not None else apply_column_naming_strategy(name, naming_rules_of(obj).columns) + + +def _is_flattened(field: MetaField) -> bool: + return ( + field.sub_type == fc.FIELD_SUBTYPE_OBJECT + and field.get_meta_attr(fc.FIELD_ATTR_STORAGE) == fc.STORAGE_FLATTENED + ) + + +def _raw_column(field: MetaData, is_pk: bool, generation: str, name: str) -> Json: + return { + "name": name, + "nullable": not is_pk and not is_required(field), + "identity": generation if is_pk and generation in (GENERATION_INCREMENT, GENERATION_UUID) else "", + "description": _description(field), + } + + +def _field_columns(field: MetaField, is_pk: bool, generation: str) -> list[Json]: + if _is_flattened(field): + target = ref_target(field, fc.FIELD_ATTR_OBJECT_REF) + if not isinstance(target, MetaObject): + return [] + return [ + _raw_column(nested, False, "", resolve_flattened_column_name(field, nested)) + for nested in target.fields() + ] + return [_raw_column(field, is_pk, generation, resolve_column_name(field))] + + +def _target_columns(ref: MetaData, target: MetaObject) -> list[str]: + """The referenced key's columns: an explicit dotted tail on ``@references``, else the + target's primary identity (its first field), else ``id``.""" + raw = ref.get_meta_attr(IDENTITY_REFERENCE_ATTR_REFERENCES) + tail = split_child_tail(raw)[1] if isinstance(raw, str) else "" + names = [s.strip() for s in tail.lstrip(".").split(",") if s.strip()] + if not names: + identity = target.primary_identity() + pk = _identity_fields(identity) if identity is not None else [] + names = [pk[0] if pk else "id"] + return [_column_of(target, n) for n in names] + + +def _is_ref(c: MetaData) -> bool: + return c.type == TYPE_IDENTITY and c.sub_type == IDENTITY_SUBTYPE_REFERENCE + + +def _foreign_keys(entity: MetaObject, objects: list[MetaObject], table_of: dict[int, str]) -> list[Json]: + refs: list[tuple[MetaObject, MetaData]] = [(entity, c) for c in entity.children() if _is_ref(c)] + if entity.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR) is not None: + base_names = {r.name for _h, r in refs} + for sub in _tph_concrete_subtypes(entity, objects): + for c in sub.children(): + if _is_ref(c) and c.name not in base_names: + refs.append((sub, c)) + fks: list[Json] = [] + for holder, ref in refs: + if ref.get_meta_attr(IDENTITY_REFERENCE_ATTR_ENFORCE) is False: + continue # a logical-only reference is no constraint + target = ref_target(ref, IDENTITY_REFERENCE_ATTR_REFERENCES) + if not isinstance(target, MetaObject): + continue + ref_table = table_of.get(id(target)) + if not ref_table: + continue + names = _identity_fields(ref) + if not names: + continue + fk: Json = { + "columns": [_column_of(holder, n) for n in names], + "refTable": ref_table, + "refColumns": _target_columns(ref, target), + "name": None, + "onDelete": None, + "onUpdate": None, + } + if fk not in fks: # two subtypes may declare the same column: one constraint + fks.append(fk) + return fks + + +def _key(name: str, schema: str) -> str: + return name if schema == "" else f"{schema}.{name}" + + +def build_storage( + root: MetaData, + node: Callable[[MetaData], Json], + member: Callable[[MetaData, MetaData], Json | None], +) -> Json: + """The storage section of the docs view for the top-level nodes of *root*, in declaration + order. *node* is a top-level node's link; *member* the link to a field as a member of its + top-level owner (its own row of an inherited one), or ``None``.""" + objects = [c for c in root.children() if isinstance(c, MetaObject)] + + # Pass 1: which objects own a table, and which are only a foreign-key target. + entities: list[tuple[MetaObject, MetaSource]] = [] + target_only: list[tuple[MetaObject, MetaSource]] = [] + tph_members: list[tuple[MetaObject, MetaData]] = [] + for obj in objects: + base = _discriminator_base(obj) + if base is not None and (_is_abstract(obj) or _is_tph_subtype(obj)): + tph_members.append((obj, base)) + continue + if _is_abstract(obj): + continue + if not any(isinstance(c, MetaSource) and c.is_writable() for c in obj.children()): + continue + source = primary_rdb_source(obj) + if source is None: + continue + # ADR-0039 sanctioned own: @unmanaged is read off the object's OWN writable source. + own = next((c for c in obj.own_children() if isinstance(c, MetaSource) and c.is_writable()), None) + if own is not None and own.is_unmanaged(): + target_only.append((obj, source)) + continue + entities.append((obj, source)) + table_of: dict[int, str] = {id(o): s.physical_name() for o, s in [*entities, *target_only]} + for m, base in tph_members: + name = table_of.get(id(base)) + if name is not None and id(m) not in table_of: + table_of[id(m)] = name + + # Every object at each storage key, in declaration order: the column -> declaring field map + # (first writer wins on a shared table) and the objects a page lists. + at_key: dict[str, list[MetaObject]] = {} + for obj in objects: + source = primary_rdb_source(obj) + if source is None: + continue + at_key.setdefault(_key(source.physical_name(), _schema_of(source)), []).append(obj) + + def field_of(k: str) -> dict[str, tuple[MetaObject, MetaField]]: + mapping: dict[str, tuple[MetaObject, MetaField]] = {} + for obj in at_key.get(k, []): + for field in obj.fields(): + column = resolve_column_name(field) + if column not in mapping: + mapping[column] = (obj, field) + return mapping + + def objects_at(k: str) -> list[Json]: + return [node(o) for o in at_key.get(k, []) if not _is_abstract(o)] + + tables: list[Json] = [] + keys: set[str] = set() + for entity, source in entities: + identity = entity.primary_identity() + pk_names = _identity_fields(identity) if identity is not None else [] + gen = identity.get_meta_attr(IDENTITY_ATTR_GENERATION) if identity is not None else None + generation = gen if isinstance(gen, str) else "" + raw: list[Json] = [] + for field in entity.fields(): + if field.is_derived(): + continue + is_pk = field.name in pk_names + raw.extend(_field_columns(field, is_pk, generation if is_pk else "")) + if entity.get_meta_attr(OBJECT_ATTR_DISCRIMINATOR) is not None: + existing = {c["name"] for c in raw} + base_fields = {f.name for f in entity.fields()} + for sub in _tph_concrete_subtypes(entity, objects): + for field in sub.fields(): + if field.name in base_fields or field.is_derived(): + continue + col = _raw_column(field, False, "", resolve_column_name(field)) + if col["name"] in existing: + continue + col["nullable"] = True # a row of any other subtype stores NULL here + raw.append(col) + existing.add(col["name"]) + schema = _schema_of(source) + k = _key(source.physical_name(), schema) + mapping = field_of(k) + columns: list[Json] = [] + for c in raw: + m = mapping.get(c["name"]) + columns.append({ + "name": c["name"], + "field": None if m is None else member(m[0], m[1]), + "nullable": c["nullable"], + "identity": c["identity"], + "description": c["description"], + "sqlType": None, + "default": None, + }) + tables.append({ + "name": source.physical_name(), + "schema": schema, + "declaredBy": node(entity), + "objects": objects_at(k), + "description": _description(entity), + "primaryKey": [_column_of(entity, n) for n in pk_names], + "columns": columns, + "foreignKeys": _foreign_keys(entity, objects, table_of), + "indexes": None, + "checks": None, + }) + keys.add(k) + + views: list[Json] = [] + for obj in objects: + if _is_abstract(obj): + continue + source = primary_rdb_source(obj) + if source is None or source.effective_kind() != _SOURCE_KIND_VIEW: + continue + schema = _schema_of(source) + k = _key(source.physical_name(), schema) + if k in keys: + continue + keys.add(k) + views.append({ + "name": source.physical_name(), + "schema": schema, + "declaredBy": node(obj), + "objects": objects_at(k), + "columns": [{"name": name, "field": member(m[0], m[1])} for name, m in field_of(k).items()], + }) + + tables.sort(key=lambda t: _cu(t["name"])) + views.sort(key=lambda v: _cu(v["name"])) + return {"physical": False, "dialect": "", "tables": tables, "views": views} diff --git a/server/python/tests/codegen/test_docs_site_generator.py b/server/python/tests/codegen/test_docs_site_generator.py index 13494a8447..eeaecb2900 100644 --- a/server/python/tests/codegen/test_docs_site_generator.py +++ b/server/python/tests/codegen/test_docs_site_generator.py @@ -50,10 +50,10 @@ def test_model_script_is_typescripts_bytes() -> None: script, stamp = explorer_model_script( "Shop ", "v1", {"b": "B\n", "a": "A é"}, {"explorer-head.mustache": ""}, expected_view("shop") ) - assert stamp == "2600a8bb3cb5d29d" - assert len(script) == 50657 - assert hashlib.sha256(script.encode("utf-8")).hexdigest() == "87643095df7b9c679871c21420f8a3ae71128ba60f71f97b2b8bc99dfc482cfb" - assert explorer_stamp_script(stamp) == 'window.MO_STAMP = "2600a8bb3cb5d29d";\n' + assert stamp == "d4fdee1b6a14ff03" + assert len(script) == 55371 + assert hashlib.sha256(script.encode("utf-8")).hexdigest() == "c3359765dc5274a1837ec945a9faa3eba528f7bd885080e6c983f06ab6694b5b" + assert explorer_stamp_script(stamp) == 'window.MO_STAMP = "d4fdee1b6a14ff03";\n' def test_app_files_are_the_canonical_copy() -> None: diff --git a/server/python/tests/conformance/test_docs_page_conformance.py b/server/python/tests/conformance/test_docs_page_conformance.py index 1c6c369497..93162e72cb 100644 --- a/server/python/tests/conformance/test_docs_page_conformance.py +++ b/server/python/tests/conformance/test_docs_page_conformance.py @@ -1,9 +1,9 @@ """Cross-port docs-page corpus: fixtures/docs-page-conformance/. -The requirements page, the agent requirements page and the MODEL-ONLY agent schema page are -shared Mustache templates fed data a per-port builder computes. TypeScript is the source of -the expected bytes; this runner holds the Python builders to them in three layers, so a -failure says where it is: the ROWS each builder starts from (JSON value equality), the PAGE +The requirements TOON page, the agent requirements page and the MODEL-ONLY agent schema page are +shared Mustache templates fed data a per-port builder reads off the docs view. TypeScript is the +source of the expected bytes; this runner holds the Python builders to them in three layers, so a +failure says where it is: the ROWS each builder reads off the view (JSON value equality), the PAGE DATA each template is fed (JSON value equality), then the BYTES. The SET of pages is pinned too: a page the case does not list must not be written. """ @@ -20,6 +20,7 @@ from metaobjects.codegen.generators.agent_docs_generator import AgentDocsGenerator from metaobjects.codegen.generators.requirements_generator import RequirementsGenerator from metaobjects.codegen.runtime.docs_requirements import ( + AGENT_REQUIREMENTS_PAGE_REF, REQUIREMENTS_PAGE_REF, REQUIREMENTS_TOON_REF, agent_requirements_page_data, @@ -28,9 +29,10 @@ requirements_toon_data, toon_cell, ) -from metaobjects.codegen.runtime.docs_schema import agent_schema_page_data, schema_rows +from metaobjects.codegen.runtime.docs_schema import AGENT_SCHEMA_PAGE_REF, agent_schema_page_data, schema_rows from metaobjects.config.neutral_config import chose_migrate_dialect -from metaobjects.render.doc_pages import doc_provider, render_doc_page +from metaobjects.docs_view import build_docs_view +from metaobjects.render.doc_pages import doc_provider, end_with_one_newline, render_doc_page def _corpus() -> Path: @@ -76,45 +78,49 @@ def test_the_corpus_is_not_empty() -> None: @pytest.mark.parametrize("case", CASES) -def test_rows_data_and_bytes(case: str) -> None: +def test_view_rows_data_and_bytes(case: str) -> None: root = _load(case) expected = _expected(case) provider = doc_provider() + has_migrate = chose_migrate_dialect(CORPUS / case / "input") + # Every page starts from the docs view; the layers are checked in order: rows, data, bytes. + view = build_docs_view(root) - rows = requirement_rows(root) + def ledger(data: dict[str, Any]) -> str: + return render_doc_page(REQUIREMENTS_PAGE_REF, data, provider, "requirements.md") + + produced: dict[str, str] = {} + rows = requirement_rows(view) if rows: assert rows == _json(expected, "rows/requirements.json"), "requirement rows" - assert requirements_ledger_data(rows) == _json(expected, "data/requirements.md.json") + assert requirements_ledger_data(rows, embedded=True) == _json(expected, "data/ledger.md.json") assert requirements_toon_data(rows) == _json(expected, "data/requirements.toon.json") - assert ( - render_doc_page(REQUIREMENTS_PAGE_REF, requirements_ledger_data(rows), provider, "requirements.md") - == expected["requirements.md"] + produced["requirements.toon"] = render_doc_page( + REQUIREMENTS_TOON_REF, requirements_toon_data(rows), provider, "requirements.toon" ) - assert ( - render_doc_page(REQUIREMENTS_TOON_REF, requirements_toon_data(rows), provider, "requirements.toon") - == expected["requirements.toon"] - ) - - def ledger(data: dict[str, Any]) -> str: - return render_doc_page(REQUIREMENTS_PAGE_REF, data, provider, "requirements.md") - - agent = agent_requirements_page_data(root, None, ledger) + agent = agent_requirements_page_data(view, None, ledger) if agent is not None: assert agent == _json(expected, "data/agent-requirements.md.json"), "agent requirements data" - - srows = schema_rows(root) - data = agent_schema_page_data(root, srows, chose_migrate_dialect(CORPUS / case / "input")) + produced["agent/requirements.md"] = render_doc_page( + AGENT_REQUIREMENTS_PAGE_REF, agent, provider, "agent/requirements.md" + ) + data = agent_schema_page_data(view, has_migrate) if data is not None: - assert srows == _json(expected, "rows/schema.json"), "schema rows" + assert schema_rows(view) == _json(expected, "rows/schema.json"), "schema rows" assert data == _json(expected, "data/agent-schema.md.json"), "schema page data" + produced["agent/schema.md"] = end_with_one_newline( + render_doc_page(AGENT_SCHEMA_PAGE_REF, data, provider, "agent/schema.md") + ) # The generators write exactly the pinned pages, byte for byte (the set is pinned too). ctx = _ctx(root, CORPUS / case / "input") written = {f.path: f.content for f in RequirementsGenerator().generate(ctx)} written.update({f.path: f.content for f in AgentDocsGenerator().generate(ctx)}) pages = {k: v for k, v in expected.items() if not k.startswith(("data/", "rows/"))} + assert sorted(produced) == sorted(pages) assert sorted(written) == sorted(pages) for path, content in pages.items(): + assert produced[path] == content, path assert written[path] == content, path @@ -148,4 +154,4 @@ def test_a_project_template_overrides_the_bundled_page(tmp_path: Path) -> None: (override / "requirements.toon.mustache").write_text("custom {{{count}}}", encoding="utf-8") files = {f.path: f.content for f in RequirementsGenerator(template_root=str(tmp_path)).generate(_ctx(root, CORPUS / "ledger-unclaimed" / "input"))} assert files["requirements.toon"] == "custom 1" - assert files["requirements.md"].startswith("# Requirements") + assert "requirements.md" not in files diff --git a/server/python/tests/unit/test_agent_docs.py b/server/python/tests/unit/test_agent_docs.py index 39b4284fdd..466def9d21 100644 --- a/server/python/tests/unit/test_agent_docs.py +++ b/server/python/tests/unit/test_agent_docs.py @@ -206,3 +206,37 @@ def test_command_writes_into_out_and_refuses_an_unknown_stack( assert main(["agent-docs", "--server", "python", "--client", "tanstack", "--out", str(tmp_path / "no")]) == 2 assert "python-react-tanstack" in capsys.readouterr().err assert not (tmp_path / "no").exists() + + +# --- the always-on pointer at the agent pages (fixtures/agent-pages-pointer/) --------------- + +POINTER_CASES = REPO_ROOT / "fixtures/agent-pages-pointer/cases" + + +def _pages_template() -> str: + tree = load_shipped() + return (tree.root / "files" / str(tree.manifest["agentPagesTemplate"])).read_text(encoding="utf-8") + + +@pytest.mark.parametrize("case", sorted(p.name for p in POINTER_CASES.iterdir() if p.is_dir())) +def test_agent_pages_section_matches_the_corpus(case: str) -> None: + from metaobjects.agent_context.agent_pages import render_agent_pages_section, wired_agent_pages + + expected = (POINTER_CASES / case / "expected-section.md").read_text(encoding="utf-8") + assert render_agent_pages_section(_pages_template(), wired_agent_pages(POINTER_CASES / case)) == expected + + +def test_the_pointer_lands_above_the_rules_and_an_empty_section_changes_nothing(tmp_path: Path) -> None: + import shutil + + plain = tmp_path / "plain" + plain.mkdir() + run_agent_docs(servers=["python"], clients=[], out=plain, version=RELEASE) + wired = tmp_path / "wired" + shutil.copytree(POINTER_CASES / "wired" / ".metaobjects", wired / ".metaobjects") + run_agent_docs(servers=["python"], clients=[], out=wired, version=RELEASE) + before = (plain / ".metaobjects/AGENTS.md").read_text(encoding="utf-8") + after = (wired / ".metaobjects/AGENTS.md").read_text(encoding="utf-8") + section = (POINTER_CASES / "wired" / "expected-section.md").read_text(encoding="utf-8") + at = before.index("\n## Rules\n") + 1 + assert after == before[:at] + section + before[at:] From 6d0f251613dbd7bfc0f4c1e353dfddfd3bc3549d Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 07:37:06 -0500 Subject: [PATCH 10/21] wip: Rust docs view storage, requirements and agent-docs from the view --- docs/ports/rust.md | 31 +- server/rust/metaobjects-cli/src/lib.rs | 2 +- server/rust/metaobjects-cli/tests/cli.rs | 6 +- .../metaobjects-codegen/src/agent_docs.rs | 121 +++ .../metaobjects-codegen/src/docs_pages.rs | 951 ++++++++++++++++++ .../rust/metaobjects-codegen/src/docs_site.rs | 4 +- server/rust/metaobjects-codegen/src/eject.rs | 27 + .../metaobjects-codegen/src/generator_list.rs | 8 +- server/rust/metaobjects-codegen/src/lib.rs | 7 + .../src/metamodel_templates.rs | 11 +- server/rust/metaobjects-codegen/src/plan.rs | 7 + .../src/requirements_docs.rs | 45 + .../metaobjects-codegen/tests/common/mod.rs | 14 +- .../tests/docs_page_conformance.rs | 181 ++++ .../metaobjects-codegen/tests/docs_site.rs | 6 +- server/rust/metaobjects/src/docs_view.rs | 39 +- .../rust/metaobjects/src/docs_view/storage.rs | 583 +++++++++++ .../tests/docs_view_conformance.rs | 4 +- 18 files changed, 2021 insertions(+), 26 deletions(-) create mode 100644 server/rust/metaobjects-codegen/src/agent_docs.rs create mode 100644 server/rust/metaobjects-codegen/src/docs_pages.rs create mode 100644 server/rust/metaobjects-codegen/src/requirements_docs.rs create mode 100644 server/rust/metaobjects-codegen/tests/docs_page_conformance.rs create mode 100644 server/rust/metaobjects/src/docs_view/storage.rs diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 2dd78f4e7e..9fc7033340 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -37,7 +37,7 @@ The loader is the `metaobjects` crate, and the workspace at `server/rust/` adds | Report shapes | `metaobjects::report_shape::report_shape` derives an `object.report`'s fields (FR-044 Table B, with Table C's `required`): each dimension and measure, its subtype, and the `@of` field it takes its type from. It byte-matches `fixtures/persistence-conformance/report-shapes.json`, as every port does. | | Docs view | `metaobjects::docs_view::build` builds the port-neutral docs view (`docs/features/docs-view.md`) from the loaded model, with the requirement ledger, the generated files and the routes when it is given them. It byte-matches `fixtures/explorer-conformance/`, as every port does. | | Metadata routes | `metaobjects::meta_endpoint` holds the bodies of `GET /_meta` (`meta_json`) and `GET /_meta/docs` (`docs`, with its ETag and the `If-None-Match` check), framework-free, for the host to mount ([Metadata API](../features/metadata-api.md#rust--axum)). | -| Code generation (`cargo meta`) | The run engine, thirteen generators (`entity`, `rules-names`, `contract-types`, `repository`, `service`, `service-routes`, `client`, `commands`, `render-helper`, `output-parser`, `output-prompt`, and two opt-in docs generators: `metamodel-docs`, the metamodel reference pages rendered from the shared Mustache set, and `docs-site`, the model explorer), the codegen and template drift gates and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | +| Code generation (`cargo meta`) | The run engine, fifteen generators (`entity`, `rules-names`, `contract-types`, `repository`, `service`, `service-routes`, `client`, `commands`, `render-helper`, `output-parser`, `output-prompt`, and four opt-in docs generators: `metamodel-docs`, the metamodel reference pages rendered from the shared Mustache set, `requirements` and `agent-docs`, the requirement and agent pages read off the docs view, and `docs-site`, the model explorer), the codegen and template drift gates and `eject`. See [The command](#the-command-cargo-meta) and [What `gen` writes](#what-gen-writes) below. | ## The command: `cargo meta` @@ -70,8 +70,8 @@ and the same `git` + `rev` on a `metaobjects` dependency). The candidate log The generators a project runs are the list in `metaobjects.config.json` at the project root, the way the other ports choose theirs (`metaobjects.config.ts`, `codegen/Generators.cs`, the pom, `metaobjects.config.yaml`). `cargo meta init` writes every shipped generator but the opt-in -ones: the transport, `service-routes`, which `cargo meta init --transport` adds, and the two docs -generators, `metamodel-docs` and `docs-site`, which you add by name. Delete a line to stop running +ones: the transport, `service-routes`, which `cargo meta init --transport` adds, and the four docs +generators, `metamodel-docs`, `requirements`, `agent-docs` and `docs-site`, which you add by name. Delete a line to stop running one, and no eject is needed: ```json @@ -81,10 +81,10 @@ one, and no eject is needed: The file takes that one key: a layer is only a generator, so there are no layer settings. An entry is a name, or `{"name": "", "options": {...}}` for a generator that takes options; the generator's `configure` reads them and refuses a key it does not know (`ERR_UNKNOWN_GENERATOR_OPTION`, -naming the options it takes). Of the shipped generators only the two docs generators take options -(`metamodel-docs` takes `subDir`; `docs-site` takes the six in [its section](#docs-site-the-model-explorer)), so +naming the options it takes). Of the shipped generators only the docs generators take options +(`metamodel-docs`, `requirements` and `agent-docs` take `subDir`; `docs-site` takes the six in [its section](#docs-site-the-model-explorer)), so any other option fails the run, also a run `--generators` narrows to other generators. A project with -no such file runs every generator but `service-routes`, `metamodel-docs` and `docs-site`, which run +no such file runs every generator but `service-routes` and the four docs generators, which run only when they are listed: an HTTP server is a choice the project makes, not a default, and so are the metamodel reference pages and the model explorer. A generator that leaves the list has its files removed on the next `gen` (a file somebody edited is refused by name instead), and the run fails, naming the @@ -487,6 +487,25 @@ An entity whose source has a read-only view beside its table (`source.rdb @kind: role) is written to the table and read back through the view, so the fields that view derives (`origin.*`) are in every answer, a write's included. +### `requirements` and `agent-docs`: the requirement and agent pages + +`requirements` writes the requirement ledger as `requirements.toon`, for tools; `agent-docs` writes +`agent/requirements.md` (the node index and the embedded ledger) and the model-only `agent/schema.md` +(tables, views, relationships and enums, without the SQL types, defaults, indexes and checks only the +TypeScript migration engine knows). Both read the docs view alone and render the shared +`templates/requirements/` and `templates/agent/` Mustache pages, so the bytes are every port's +(`fixtures/docs-page-conformance/`, run by `tests/docs_page_conformance.rs`). A same-path file under +the project's `templates/` wins. No `requirement.*` node, no requirement page; no table and no view, +no schema page. The schema page says to change the schema with `meta migrate` when +`.metaobjects/config.json` sets `migrate.dialect`. Nobody reads a human `requirements.md` any more: +the explorer shows the ledger. `agent/ui.md` stays a TypeScript page. + +What is absent here: this port has no requirement ledger of its own (no `requirements.inherit` +collection and no requirement gate in `cargo meta verify`, the RS-V2 work), so the pages list every +requirement the view carries, an imported package's included, where a port with the ledger lists +only those the collection counts. The project has no always-on agent file to point at the pages +either: `cargo meta` scaffolds no agent context. + ### `docs-site`: the model explorer The model explorer ([Explorer site](../features/explorer-site.md)), written with no Node: the diff --git a/server/rust/metaobjects-cli/src/lib.rs b/server/rust/metaobjects-cli/src/lib.rs index 4ea4c4c6ca..be3f03cc8a 100644 --- a/server/rust/metaobjects-cli/src/lib.rs +++ b/server/rust/metaobjects-cli/src/lib.rs @@ -96,7 +96,7 @@ OPTIONS (everywhere): GENERATORS: a project chooses what runs in metaobjects.config.json, `{ \"generators\": [..] }`, by name. Edit the list; no eject is needed. With no such file every generator runs but the opt-in ones: the transport (service-routes), which `init --transport` lists, and the docs -generators (metamodel-docs, docs-site), which run only when listed. +generators (metamodel-docs, requirements, agent-docs, docs-site), which run only when listed. ENTITY names limit `gen` to the crates that contain them plus the crates those depend on. Such a run never skips, never stores the skip key and never removes a file. diff --git a/server/rust/metaobjects-cli/tests/cli.rs b/server/rust/metaobjects-cli/tests/cli.rs index 2293061043..fcf105c1e6 100644 --- a/server/rust/metaobjects-cli/tests/cli.rs +++ b/server/rust/metaobjects-cli/tests/cli.rs @@ -278,7 +278,7 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl "{out}" ); assert_eq!(out.matches("[configured]").count(), 10, "{out}"); - assert_eq!(out.matches("[not configured]").count(), 3, "{out}"); + assert_eq!(out.matches("[not configured]").count(), 5, "{out}"); assert!( out.contains("(layer: docs) [not configured] [package-only]"), "docs-site is listed as package-only: {out}" @@ -295,7 +295,7 @@ fn init_writes_the_generator_list_and_gen_list_shows_it_against_what_is_availabl ); let out = ok(&p.run(&["meta", "gen", "--list"])); assert!(out.contains("runs: entity\n"), "{out}"); - assert_eq!(out.matches("[not configured]").count(), 12, "{out}"); + assert_eq!(out.matches("[not configured]").count(), 14, "{out}"); } #[test] @@ -598,7 +598,7 @@ fn eject_copies_the_generator_never_overwrites_and_undo_takes_back_only_identica assert_eq!(r.status.code(), Some(2)); assert!( text(&r.stderr).contains( - "unknown or non-ejectable generator(s): nope; ejectable: entity, rules-names, contract-types, repository, service, service-routes, client, commands, render-helper, output-parser, output-prompt, metamodel-docs" + "unknown or non-ejectable generator(s): nope; ejectable: entity, rules-names, contract-types, repository, service, service-routes, client, commands, render-helper, output-parser, output-prompt, metamodel-docs, requirements, agent-docs" ), "{}", text(&r.stderr) diff --git a/server/rust/metaobjects-codegen/src/agent_docs.rs b/server/rust/metaobjects-codegen/src/agent_docs.rs new file mode 100644 index 0000000000..731964764f --- /dev/null +++ b/server/rust/metaobjects-codegen/src/agent_docs.rs @@ -0,0 +1,121 @@ +//! The `agent-docs` generator: pages written for a coding agent working in the project. +//! +//! In Rust it writes two pages under `agent/`: `agent/requirements.md` (the node index, the +//! statements and the embedded ledger, read before adding a capability) and `agent/schema.md` +//! (the MODEL-ONLY schema page: the tables, columns, keys, views, relationships and enums the +//! model declares, read before touching persistence; no SQL type, default, index, check or +//! constraint name, which only the TypeScript page, written from the expected schema, carries). +//! `agent/ui.md` stays TypeScript-only. +//! +//! Each page is a shared Mustache template (`templates/agent/`, `templates/requirements/`) +//! fed the data the docs page builders read off the docs view, pinned by +//! `fixtures/docs-page-conformance/`. A page with nothing to describe is no file. A project's +//! own same-named template wins over the shipped one. + +use metaobjects_codegen::generator::{ + EmittedFile, GenContext, GenError, Generator, Options, unknown_options, +}; +use metaobjects_codegen::plan::{ + DocsTemplates, agent_requirements_page, agent_schema_page, has_migrate, view_of, +}; + +/// Bump when the emitted text changes shape, so a stored skip key never survives it. +const FORMAT: u32 = 1; + +const DEFAULT_DIR: &str = "agent"; +const OPTION_SUB_DIR: &str = "subDir"; +const ERR_AGENT_DOCS: &str = "ERR_AGENT_DOCS"; +/// What the pages read besides the model: the templates, and `migrate.dialect` of the config. +const INPUTS: [&str; 3] = [ + "templates/agent", + "templates/requirements", + ".metaobjects/config.json", +]; + +/// The agent-docs generator. +#[derive(Debug, Clone, Copy, Default)] +pub struct AgentDocsGenerator; + +/// The generator as a project configured it (`{"name": "agent-docs", "options": {"subDir": ""}}`). +#[derive(Debug, Clone)] +pub struct ConfiguredAgentDocs { + dir: String, +} + +impl Generator for AgentDocsGenerator { + fn name(&self) -> &str { + "agent-docs" + } + + fn identity(&self) -> String { + format!("agent-docs:{FORMAT}:{DEFAULT_DIR}") + } + + fn extra_inputs(&self) -> Vec { + INPUTS.iter().map(ToString::to_string).collect() + } + + fn configure(&self, options: &Options) -> Result, GenError> { + if options.keys().any(|k| k != OPTION_SUB_DIR) { + return Err(unknown_options(self.name(), options, &[OPTION_SUB_DIR])); + } + let dir = match options.get(OPTION_SUB_DIR) { + None => DEFAULT_DIR.to_string(), + Some(serde_json::Value::String(s)) => s.trim_matches('/').to_string(), + Some(other) => { + return Err(GenError::new( + ERR_AGENT_DOCS, + format!( + "the generator agent-docs takes \"{OPTION_SUB_DIR}\" as a string, got {other}" + ), + )); + } + }; + Ok(Box::new(ConfiguredAgentDocs { dir })) + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + pages_under(DEFAULT_DIR, ctx) + } +} + +impl Generator for ConfiguredAgentDocs { + fn name(&self) -> &str { + "agent-docs" + } + + fn identity(&self) -> String { + format!("agent-docs:{FORMAT}:{}", self.dir) + } + + fn extra_inputs(&self) -> Vec { + INPUTS.iter().map(ToString::to_string).collect() + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + pages_under(&self.dir, ctx) + } +} + +/// Every page that has something to describe, under `dir` of the output (`""` for its root). +fn pages_under(dir: &str, ctx: &GenContext<'_>) -> Result, GenError> { + let at = |name: &str| { + if dir.is_empty() { + name.to_string() + } else { + format!("{dir}/{name}") + } + }; + let view = view_of(ctx); + let templates = DocsTemplates::new(ctx); + let mut files = Vec::new(); + let path = at("schema.md"); + if let Some(page) = agent_schema_page(&view, has_migrate(ctx), &templates, &path)? { + files.push(EmittedFile::new(path, page)); + } + let path = at("requirements.md"); + if let Some(page) = agent_requirements_page(&view, &templates, &path)? { + files.push(EmittedFile::new(path, page)); + } + Ok(files) +} diff --git a/server/rust/metaobjects-codegen/src/docs_pages.rs b/server/rust/metaobjects-codegen/src/docs_pages.rs new file mode 100644 index 0000000000..0b79a1628b --- /dev/null +++ b/server/rust/metaobjects-codegen/src/docs_pages.rs @@ -0,0 +1,951 @@ +//! The documentation pages written from the docs view: `requirements.toon`, +//! `agent/requirements.md` (with the ledger it embeds) and the model-only `agent/schema.md`. +//! +//! The port of TypeScript's `docs-view-pages.ts`, `requirements-markdown.ts`, +//! `requirements-toon.ts` and `agent-requirements-page.ts`, over the view +//! ([`metaobjects::docs_view::build`]) and nothing else: the requirement rows come from its +//! `requirements`, the node index from each requirement's resolved `implementedBy`, and the +//! schema from its `storage` plus the members of the nodes it links. Every page is a shared +//! Mustache template (`templates/requirements/`, `templates/agent/`, embedded in +//! [`crate::metamodel_templates`]) fed the data built here; the builder makes every decision +//! (heading depth, which title survives, the fact bar, the demotion of the embedded ledger, +//! every table cell, TOON quoting) and the template only lays the lines out. Rows and data are +//! pinned by `fixtures/docs-page-conformance/`. +//! +//! Rust holds no requirement ledger of its own (the resolved gate is not ported), so the rows are +//! every `requirement.*` node of the model, and a dependency's requirement the project did not +//! inherit is not left out. + +use std::collections::HashMap; + +use metaobjects::docs_view; +use metaobjects::naming::NamingRegistry; +use metaobjects_render::{Body, Provider, RenderRequest, render}; +use serde_json::{Map, Value, json}; + +use crate::generator::{GenContext, GenError}; +use crate::metamodel_templates::shipped_template; + +/// The shared templates, by ref. +pub const REQUIREMENTS_PAGE_REF: &str = "requirements/requirements.md"; +pub const REQUIREMENTS_TOON_REF: &str = "requirements/requirements.toon"; +pub const AGENT_REQUIREMENTS_PAGE_REF: &str = "agent/requirements.md"; +pub const AGENT_SCHEMA_PAGE_REF: &str = "agent/schema.md"; + +/// The marker on the first line of every agent page. It is part of the shared contract: the +/// corpus pins it byte for byte. +pub const GENERATED_MARKER: &str = + ""; + +const REQUIREMENTS_TOON_FIELDS: [&str; 7] = [ + "path", + "subType", + "level", + "status", + "disposition", + "claims", + "statement", +]; + +fn s<'a>(v: &'a Value, key: &str) -> &'a str { + v.get(key).and_then(Value::as_str).unwrap_or_default() +} + +fn arr<'a>(v: &'a Value, key: &str) -> &'a [Value] { + v.get(key) + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice) +} + +/// JavaScript's string order: by UTF-16 code unit. +fn by_code_unit(a: &str, b: &str) -> std::cmp::Ordering { + a.encode_utf16().cmp(b.encode_utf16()) +} + +/// `text.replace(/\s+/g, " ").trim()`. +fn one_line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +fn md_cell(text: &str) -> String { + text.replace('|', "\\|") +} + +// ---- rows ----------------------------------------------------------------------------- + +/// A view string as a row value: "" is absent. +fn put_opt(row: &mut Map, key: &str, text: &str) { + if !text.is_empty() { + row.insert(key.to_string(), Value::String(text.to_string())); + } +} + +/// Every requirement of the view, nested ones included, as render-ready rows in document +/// order. An empty list for a model declaring none, which is what lets the surface write +/// nothing. A value the TypeScript leaves `undefined` is an ABSENT key here. +pub fn requirement_rows(view: &Value) -> Vec { + arr(view, "requirements") + .iter() + .map(|r| { + let mut row = Map::new(); + row.insert("path".into(), json!(s(r, "address"))); + row.insert("depth".into(), r["depth"].clone()); + put_opt(&mut row, "title", s(r, "title")); + row.insert("subType".into(), json!(s(r, "subType"))); + if !r["level"].is_null() { + row.insert("level".into(), r["level"].clone()); + } + put_opt(&mut row, "status", s(r, "status")); + put_opt(&mut row, "disposition", s(r, "disposition")); + row.insert("trackedBy".into(), r["trackedBy"].clone()); + put_opt(&mut row, "statement", s(r, "statement")); + put_opt(&mut row, "counterexample", s(r, "counterexample")); + put_opt(&mut row, "description", s(r, "description")); + let claims = arr(r, "implementedBy"); + row.insert( + "implementedBy".into(), + Value::Array(claims.iter().map(|l| json!(s(l, "ref"))).collect()), + ); + let mut concerns: Vec<&str> = Vec::new(); + for l in claims.iter().filter(|l| l["resolves"] == Value::Bool(true)) { + let kind = s(&l["target"], "kind"); + if !concerns.contains(&kind) { + concerns.push(kind); + } + } + row.insert("claimedConcerns".into(), json!(concerns)); + Value::Object(row) + }) + .collect() +} + +// ---- requirements.md (the ledger) ----------------------------------------------------- + +/// `##` for a root-level requirement, deepening with nesting; `#` is the page title. +fn heading(depth: u64) -> String { + "#".repeat(usize::try_from(depth + 2).unwrap_or(6).min(6)) +} + +fn normalize_name(text: &str) -> String { + text.to_lowercase() + .chars() + .filter(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + .collect() +} + +/// True when the title says nothing the path's LEAF segment does not already say. +fn title_restates_leaf(path: &str, title: &str) -> bool { + let leaf = path.rfind('.').map_or(path, |i| &path[i + 1..]); + normalize_name(leaf) == normalize_name(title) +} + +fn heading_line(row: &Value) -> String { + let title = one_line(s(row, "title")); + let path = s(row, "path"); + let label = if title.is_empty() || title_restates_leaf(path, &title) { + String::new() + } else { + format!(" \u{2014} {title}") + }; + format!( + "{} {path}{label}", + heading(row["depth"].as_u64().unwrap_or(0)) + ) +} + +fn facts(row: &Value) -> String { + let mut parts = vec![format!("`{}`", s(row, "subType"))]; + if let Some(level) = row.get("level") { + parts.push(format!("**L{}**", metaobjects::json::js_display(level))); + } + if let Some(status) = row.get("status").and_then(Value::as_str) { + parts.push(format!("status: `{status}`")); + } + if let Some(d) = row.get("disposition").and_then(Value::as_str) { + parts.push(format!("disposition: `{d}`")); + } + let tracked: Vec<&str> = arr(row, "trackedBy") + .iter() + .filter_map(Value::as_str) + .collect(); + if !tracked.is_empty() { + parts.push(format!("tracked: {}", tracked.join(", "))); + } + parts.join(" \u{b7} ") +} + +/// One extra `#` on every line that starts a heading, capped at h6. +fn demote(text: &str) -> String { + let mut out = String::with_capacity(text.len() + 4); + let mut at_line_start = true; + let mut rest = text; + while !rest.is_empty() { + if at_line_start { + let hashes = rest.bytes().take_while(|&b| b == b'#').count(); + if (1..=6).contains(&hashes) && rest[hashes..].starts_with(' ') { + out.push_str(&"#".repeat((hashes + 1).min(6))); + rest = &rest[hashes..]; + } + } + let Some(c) = rest.chars().next() else { break }; + out.push(c); + // The line terminators of a JavaScript multiline `^`. + at_line_start = matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}'); + rest = &rest[c.len_utf8()..]; + } + out +} + +fn entry_of(row: &Value, embedded: bool) -> Value { + let line = |t: String| if embedded { demote(&t) } else { t }; + let mut entry = Map::new(); + entry.insert("heading".into(), json!(line(heading_line(row)))); + entry.insert("facts".into(), json!(line(facts(row)))); + if let Some(t) = row.get("statement").and_then(Value::as_str) { + entry.insert("statement".into(), json!(line(t.to_string()))); + } + if let Some(t) = row.get("counterexample").and_then(Value::as_str) { + entry.insert( + "counterexample".into(), + json!(line(format!("**Counterexample:** {t}"))), + ); + } + if let Some(t) = row.get("description").and_then(Value::as_str) { + entry.insert("description".into(), json!(line(t.to_string()))); + } + let refs: Vec = arr(row, "implementedBy") + .iter() + .filter_map(Value::as_str) + .map(|c| format!("`{c}`")) + .collect(); + if !refs.is_empty() { + entry.insert( + "implementedBy".into(), + json!(line(format!("**Implemented by:** {}", refs.join(", ")))), + ); + } + Value::Object(entry) +} + +/// What `requirements/requirements.md.mustache` renders. `embedded` is the ledger as a section +/// of a larger page: no `# Requirements` title, every heading one level down. +pub fn requirements_ledger_data(rows: &[Value], embedded: bool) -> Value { + json!({ + "embedded": embedded, + "count": rows.len(), + "plural": if rows.len() == 1 { "" } else { "s" }, + "entries": rows.iter().map(|r| entry_of(r, embedded)).collect::>(), + }) +} + +// ---- requirements.toon ---------------------------------------------------------------- + +/// One cell as TOON writes it inside a comma-delimited row: a number bare, a string bare when +/// it is safe and quoted (with TOON's escapes) when it is not. +fn toon_cell(value: &Value) -> String { + let Value::String(text) = value else { + return metaobjects::json::js_display(value); + }; + if toon_is_safe(text) { + return text.clone(); + } + let mut out = String::from("\""); + for ch in text.chars() { + match ch { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +/// `-?[0-9]+(\.[0-9]+)?(e[+-]?[0-9]+)?`, case-insensitively, over the whole text. +fn numeric_like(text: &str) -> bool { + let b = text.as_bytes(); + let mut i = usize::from(b.first() == Some(&b'-')); + let digits = |i: &mut usize| { + let start = *i; + while *i < b.len() && b[*i].is_ascii_digit() { + *i += 1; + } + *i > start + }; + if !digits(&mut i) { + return false; + } + if b.get(i) == Some(&b'.') { + i += 1; + if !digits(&mut i) { + return false; + } + } + if matches!(b.get(i), Some(b'e' | b'E')) { + i += 1; + if matches!(b.get(i), Some(b'+' | b'-')) { + i += 1; + } + if !digits(&mut i) { + return false; + } + } + i == b.len() +} + +/// All digits with a leading zero (`007`): a TOON reader would take it for a number. +fn leading_zero_digits(text: &str) -> bool { + text.starts_with('0') && text.bytes().all(|b| b.is_ascii_digit()) +} + +fn toon_is_safe(text: &str) -> bool { + !text.is_empty() + && text.trim() == text + && !matches!(text, "true" | "false" | "null") + && !numeric_like(text) + && !leading_zero_digits(text) + && !text.starts_with('-') + && !text.chars().any(|c| { + matches!(c, ':' | '"' | '\\' | '[' | ']' | '{' | '}' | ',') || (c as u32) < 0x20 + }) +} + +/// What `requirements/requirements.toon.mustache` renders: every cell a finished literal. +pub fn requirements_toon_data(rows: &[Value]) -> Value { + let lines: Vec = rows + .iter() + .map(|r| { + let text = |key: &str| json!(r.get(key).and_then(Value::as_str).unwrap_or_default()); + let claims: Vec<&str> = arr(r, "implementedBy") + .iter() + .filter_map(Value::as_str) + .collect(); + let cells = [ + json!(s(r, "path")), + json!(s(r, "subType")), + r.get("level").cloned().unwrap_or_else(|| json!("")), + text("status"), + text("disposition"), + json!(claims.join(" ")), + text("statement"), + ]; + let line: Vec = cells.iter().map(toon_cell).collect(); + json!({ "line": line.join(",") }) + }) + .collect(); + json!({ + "count": rows.len(), + "fields": format!("{{{}}}", REQUIREMENTS_TOON_FIELDS.join(",")), + "rows": lines, + }) +} + +// ---- agent/requirements.md ------------------------------------------------------------ + +/// Claimed node to the requirements that claim it, sorted by the node's id. A claim that does +/// not resolve is left out (`meta verify` reports it). +fn node_index(view: &Value) -> Vec<(String, String, Vec)> { + let mut by_address: Vec<(String, String, Vec)> = Vec::new(); + let mut at: HashMap = HashMap::new(); + for r in arr(view, "requirements") { + for link in arr(r, "implementedBy") { + if link["resolves"] != Value::Bool(true) { + continue; + } + let target = &link["target"]; + let id = s(target, "id").to_string(); + let i = *at.entry(id.clone()).or_insert_with(|| { + by_address.push((id, s(target, "kind").to_string(), Vec::new())); + by_address.len() - 1 + }); + by_address[i].2.push(json!({ + "path": s(r, "address"), + "subType": s(r, "subType"), + "level": r["level"], + "status": s(r, "status"), + "statement": s(r, "statement"), + })); + } + } + by_address.sort_by(|a, b| by_code_unit(&a.0, &b.0)); + by_address +} + +/// The data `agent/requirements.md.mustache` renders, or `None` for a model declaring no +/// requirements (no page). `render_ledger` renders the `requirements` template from ledger +/// data, so the embedded ledger is that page's own template and cannot disagree with it. +pub fn agent_requirements_page_data( + view: &Value, + render_ledger: impl Fn(&Value) -> Result, +) -> Result, E> { + let rows = requirement_rows(view); + if rows.is_empty() { + return Ok(None); + } + let index = node_index(view); + // The statements ride below the table: they are prose, and they repeat across nodes a + // shared architectural entry claims. + let mut stated: Vec<(String, String, String)> = Vec::new(); + for (_, _, claims) in &index { + for c in claims { + let statement = s(c, "statement"); + if statement.is_empty() { + continue; + } + let path = s(c, "path").to_string(); + let entry = ( + path.clone(), + s(c, "subType").to_string(), + statement.to_string(), + ); + match stated.iter_mut().find(|e| e.0 == path) { + Some(e) => *e = entry, + None => stated.push(entry), + } + } + } + stated.sort_by(|a, b| by_code_unit(&a.0, &b.0)); + let statements: Vec = stated + .iter() + .map(|(path, sub_type, statement)| { + json!({ "path": path, "subType": sub_type, "statement": md_cell(&one_line(statement)) }) + }) + .collect(); + let node_index: Vec = index + .iter() + .map(|(address, concern, claims)| { + let cells: Vec = claims + .iter() + .map(|c| { + let level = c["level"] + .as_i64() + .map_or(String::new(), |l| format!(" L{l}")); + let status = match s(c, "status") { + "" => String::new(), + st => format!(" ({st})"), + }; + format!("`{}`{level}{status}", s(c, "path")) + }) + .collect(); + json!({ "address": address, "concern": concern, "claims": cells.join("
    ") }) + }) + .collect(); + let ledger = render_ledger(&requirements_ledger_data(&rows, true))?; + Ok(Some(json!({ + "generatedMarker": GENERATED_MARKER, + "hasNodeIndex": !node_index.is_empty(), + "nodeIndex": node_index, + "hasStatements": !statements.is_empty(), + "statements": statements, + "ledger": ledger.trim_end_matches('\n'), + }))) +} + +// ---- schema --------------------------------------------------------------------------- + +fn storage_key(name: &str, schema: &str) -> String { + if schema.is_empty() { + name.to_string() + } else { + format!("{schema}.{name}") + } +} + +/// The rows layer of the schema page, read off the view's storage: the shape `meta schema --as +/// json` prints, less its physical facts. +pub fn schema_rows(view: &Value) -> Value { + let storage = &view["storage"]; + let mut declared: Vec<(String, String)> = Vec::new(); + let mut tables = Vec::new(); + for t in arr(storage, "tables") { + declared.push(( + storage_key(s(t, "name"), s(t, "schema")), + s(&t["declaredBy"], "id").to_string(), + )); + let mut row = Map::new(); + row.insert("name".into(), json!(s(t, "name"))); + put_opt(&mut row, "schema", s(t, "schema")); + put_opt(&mut row, "description", s(t, "description")); + row.insert("primaryKey".into(), t["primaryKey"].clone()); + let columns: Vec = arr(t, "columns") + .iter() + .map(|c| { + let mut col = Map::new(); + col.insert("name".into(), json!(s(c, "name"))); + col.insert("nullable".into(), c["nullable"].clone()); + put_opt(&mut col, "identity", s(c, "identity")); + put_opt(&mut col, "description", s(c, "description")); + Value::Object(col) + }) + .collect(); + row.insert("columns".into(), Value::Array(columns)); + let fks: Vec = arr(t, "foreignKeys") + .iter() + .map(|f| json!({ "columns": f["columns"], "refTable": f["refTable"], "refColumns": f["refColumns"] })) + .collect(); + row.insert("foreignKeys".into(), Value::Array(fks)); + tables.push(Value::Object(row)); + } + let mut views = Vec::new(); + for v in arr(storage, "views") { + declared.push(( + storage_key(s(v, "name"), s(v, "schema")), + s(&v["declaredBy"], "id").to_string(), + )); + let mut row = Map::new(); + row.insert("name".into(), json!(s(v, "name"))); + put_opt(&mut row, "schema", s(v, "schema")); + views.push(Value::Object(row)); + } + declared.sort_by(|a, b| by_code_unit(&a.0, &b.0)); + json!({ + "tables": tables, + "views": views, + "declaredBy": declared.into_iter().map(|(k, v)| (k, Value::String(v))).collect::>(), + }) +} + +/// Every member of every node, by id. +fn members_by_id(view: &Value) -> HashMap<&str, &Value> { + fn visit<'a>(m: &'a Value, out: &mut HashMap<&'a str, &'a Value>) { + out.insert(s(m, "id"), m); + for g in arr(m, "memberGroups") { + for c in arr(g, "members") { + visit(c, out); + } + } + } + let mut out = HashMap::new(); + for n in arr(view, "nodes") { + for g in arr(n, "memberGroups") { + for m in arr(g, "members") { + visit(m, &mut out); + } + } + } + out +} + +fn direct_members<'a>(n: &'a Value, type_name: &str) -> &'a [Value] { + arr(n, "memberGroups") + .iter() + .find(|g| s(g, "type") == type_name) + .map_or(&[], |g| arr(g, "members")) +} + +fn attr_value<'a>(attrs: &'a [Value], name: &str) -> Option<&'a Value> { + attrs + .iter() + .find(|a| s(a, "name") == name) + .map(|a| &a["value"]) +} + +/// A string attribute as a page prints it: a resolved reference by its link's label (what the +/// author wrote, relative to the model), anything else as its text. +fn attr_text(attrs: &[Value], name: &str) -> Option { + let a = attrs.iter().find(|a| s(a, "name") == name)?; + let value = a["value"].as_str()?; + let link = arr(a, "values").first().map(|v| &v["link"]); + let text = match link { + Some(l) if l.is_object() && l["unresolved"] != Value::Bool(true) => s(l, "label"), + _ => value, + }; + (!text.is_empty()).then(|| text.to_string()) +} + +fn cols(names: &[Value]) -> String { + if names.is_empty() { + return "\u{2014}".to_string(); + } + names + .iter() + .map(|c| format!("`{}`", c.as_str().unwrap_or_default())) + .collect::>() + .join(", ") +} + +fn key_cell(table: &Value, column: &str) -> String { + let pk = arr(table, "primaryKey"); + let mut roles: Vec = Vec::new(); + if pk.iter().any(|c| c.as_str() == Some(column)) { + roles.push(if pk.len() > 1 { "PK (composite)" } else { "PK" }.to_string()); + } + if let Some(fk) = arr(table, "foreignKeys") + .iter() + .find(|f| arr(f, "columns").iter().any(|c| c.as_str() == Some(column))) + { + roles.push(format!("FK \u{2192} `{}`", s(fk, "refTable"))); + } + roles.join(" \u{b7} ") +} + +/// The lineage text of a view column, from its field's `origin.*` member. +fn lineage_of(field: Option<&Value>) -> Option { + let origin = direct_members(field?, "origin").first()?; + let attrs = arr(origin, "attrs"); + let t = |name: &str| attr_text(attrs, name); + let via = |t: &dyn Fn(&str) -> Option| { + t("via").map_or(String::new(), |v| format!(" via `{v}`")) + }; + Some(match s(origin, "subType") { + "passthrough" => format!( + "passthrough from `{}`{}", + t("from").unwrap_or_else(|| "?".into()), + via(&t) + ), + "aggregate" => format!( + "`{}`{}{}", + t("agg").unwrap_or_else(|| "?".into()), + t("of").map_or(String::new(), |v| format!(" of `{v}`")), + via(&t) + ), + "first" => format!( + "first{}{}{}", + t("of").map_or(String::new(), |v| format!(" `{v}`")), + via(&t), + t("orderBy").map_or(String::new(), |v| format!(" ordered by `{v}`")) + ), + "computed" => "computed from a declared `@expr`".to_string(), + other => format!("`origin.{other}`"), + }) +} + +fn cardinality_phrase(cardinality: Option<&Value>, through: bool) -> &'static str { + match cardinality.and_then(Value::as_str) { + Some("many") if through => "many-to-many", + Some("many") => "one-to-many", + Some("one") => "many-to-one", + _ => "cardinality not declared", + } +} + +/// The data `agent/schema.md.mustache` renders for the model-only page, built from the view +/// alone. `has_migrate`: the project chose a `meta migrate` dialect (`migrate.dialect` in +/// `.metaobjects/config.json`). `None` when the model declares no table and no view: no page. +pub fn agent_schema_page_data(view: &Value, has_migrate: bool) -> Option { + let storage = &view["storage"]; + let tables = arr(storage, "tables"); + let views = arr(storage, "views"); + if tables.is_empty() && views.is_empty() { + return None; + } + let members = members_by_id(view); + let mut by_order: Vec<&Value> = arr(view, "nodes").iter().collect(); + by_order.sort_by_key(|n| n["order"].as_u64().unwrap_or(0)); + + let table_data: Vec = tables + .iter() + .map(|t| { + let k = storage_key(s(t, "name"), s(t, "schema")); + let described: Vec<&Value> = arr(t, "columns") + .iter() + .filter(|c| !s(c, "description").is_empty()) + .collect(); + let fks: Vec = arr(t, "foreignKeys") + .iter() + .map(|f| { + format!( + "{} \u{2192} `{}`({})", + cols(arr(f, "columns")), + s(f, "refTable"), + cols(arr(f, "refColumns")) + ) + }) + .collect(); + let columns: Vec = arr(t, "columns") + .iter() + .map(|c| { + let field = &c["field"]; + let (field_cell, declared_cell) = if field.is_null() { + (String::new(), String::new()) + } else { + let name = members.get(s(field, "id")).map_or("", |m| s(m, "name")); + (format!("`{name}`"), format!("`{}`", s(field, "kind"))) + }; + json!({ + "name": s(c, "name"), + "fieldCell": field_cell, + "declaredCell": declared_cell, + "sqlTypeCell": "", + "nullCell": if c["nullable"] == Value::Bool(true) { "yes" } else { "no" }, + "defaultCell": "", + "keyCell": key_cell(t, s(c, "name")), + }) + }) + .collect(); + let mut row = Map::new(); + row.insert("heading".into(), json!(format!("`{k}`"))); + row.insert("tableDeclaredBy".into(), json!(s(&t["declaredBy"], "id"))); + if !s(t, "description").is_empty() { + row.insert("tableDescription".into(), json!(one_line(s(t, "description")))); + } + row.insert("columns".into(), Value::Array(columns)); + row.insert("hasDescribed".into(), json!(!described.is_empty())); + row.insert( + "described".into(), + Value::Array( + described + .iter() + .map(|c| json!({ "name": s(c, "name"), "text": one_line(s(c, "description")) })) + .collect(), + ), + ); + row.insert("hasIndexes".into(), json!(false)); + row.insert("indexes".into(), json!([])); + row.insert("hasForeignKeys".into(), json!(!fks.is_empty())); + row.insert("foreignKeys".into(), json!(fks)); + row.insert("hasChecks".into(), json!(false)); + row.insert("checks".into(), json!([])); + Value::Object(row) + }) + .collect(); + + let view_data: Vec = views + .iter() + .map(|v| { + let lineage: Vec = arr(v, "columns") + .iter() + .filter_map(|c| { + let field = (!c["field"].is_null()) + .then(|| members.get(s(&c["field"], "id")).copied()) + .flatten(); + lineage_of(field).map(|text| json!({ "column": s(c, "name"), "text": text })) + }) + .collect(); + json!({ + "heading": format!("`{}`", storage_key(s(v, "name"), s(v, "schema"))), + "viewDeclaredBy": s(&v["declaredBy"], "id"), + "hasLineage": !lineage.is_empty(), + "lineage": lineage, + }) + }) + .collect(); + + // Every relationship as written, in declaration order of its object. + let mut relationships: Vec = Vec::new(); + for n in &by_order { + if s(n, "type") != "object" { + continue; + } + for rel in direct_members(n, "relationship") { + let attrs = arr(rel, "attrs"); + let through = attr_text(attrs, "through"); + let mut parts = vec![ + format!("`{}.{}`", s(n, "id"), s(rel, "name")), + format!("`{}`", s(rel, "subType")), + format!( + "{} \u{2192} `{}`", + cardinality_phrase(attr_value(attrs, "cardinality"), through.is_some()), + attr_text(attrs, "objectRef").unwrap_or_else(|| "?".into()) + ), + ]; + if let Some(t) = &through { + parts.push(format!("through `{t}`")); + } + if let Some(d) = attr_text(attrs, "onDelete") { + parts.push(format!("on delete `{d}`")); + } + relationships.push(parts.join(" \u{b7} ")); + } + } + + // Every enum field of a table-backed object, in declaration order of its object. + let table_backed: Vec<&str> = tables + .iter() + .flat_map(|t| arr(t, "objects").iter().map(|o| s(o, "id"))) + .collect(); + let mut enums: Vec = Vec::new(); + for n in &by_order { + if !table_backed.contains(&s(n, "id")) { + continue; + } + for f in direct_members(n, "field") { + if s(f, "subType") != "enum" { + continue; + } + let attrs = arr(f, "attrs"); + let list: Vec = match attr_value(attrs, "values") { + Some(Value::Array(items)) => { + items.iter().map(metaobjects::json::js_display).collect() + } + _ => Vec::new(), + }; + if list.is_empty() { + continue; + } + let storage = match attr_value(attrs, "intValueMap") { + Some(Value::Object(map)) => format!( + "int-backed ({})", + list.iter() + .map(|m| format!( + "{m}={}", + map.get(m) + .map_or("undefined".to_string(), metaobjects::json::js_display) + )) + .collect::>() + .join(", ") + ), + _ => "string-backed".to_string(), + }; + enums.push(json!({ + "field": format!("{}.{}", s(n, "id"), s(f, "name")), + "members": list.iter().map(|m| format!("`{m}`")).collect::>().join(", "), + "storage": storage, + })); + } + } + + let any_description = tables.iter().any(|t| { + !s(t, "description").is_empty() + || arr(t, "columns") + .iter() + .any(|c| !s(c, "description").is_empty()) + }); + Some(json!({ + "generatedMarker": GENERATED_MARKER, + "physical": false, + "dialect": "", + "hasMigrate": has_migrate, + "descriptionNudge": !any_description && !tables.is_empty(), + "hasTables": !table_data.is_empty(), + "tables": table_data, + "hasViews": !view_data.is_empty(), + "hasReportView": views.iter().any(|v| arr(v, "objects").iter().any(|o| s(o, "kind") == "object.report")), + "views": view_data, + "hasRelationships": !relationships.is_empty(), + "relationships": relationships, + "hasEnums": !enums.is_empty(), + "enums": enums, + })) +} + +/// A page ends with exactly one of its own line breaks (the templates end with one, so a page +/// always has one to keep); a page that ends without a break is returned as is. +pub fn end_with_one_newline(page: &str) -> String { + let body = page.trim_end_matches('\n').len(); + let keep = if body < page.len() { body + 1 } else { body }; + page[..keep].to_string() +} + +// ---- running the pages ---------------------------------------------------------------- + +/// Where a project's own templates live, from the project root. A same-named +/// `templates/.mustache` wins over the shipped one. +pub const TEMPLATE_DIR: &str = "templates"; +/// The failure of the docs page generators. +pub const ERR_DOC_PAGE: &str = "ERR_DOC_PAGE"; + +/// Resolves a template ref: the project's `templates/.mustache` if it has one, else the +/// shipped text. +pub struct DocsTemplates { + project_templates: std::path::PathBuf, +} + +impl DocsTemplates { + pub fn new(ctx: &GenContext<'_>) -> Self { + Self { + project_templates: ctx.collection.config_dir.join(TEMPLATE_DIR), + } + } +} + +impl Provider for DocsTemplates { + fn resolve(&self, reference: &str) -> Option { + std::fs::read_to_string(self.project_templates.join(format!("{reference}.mustache"))) + .ok() + .or_else(|| shipped_template(reference).map(str::to_string)) + } +} + +/// The docs view of the run's model, with the project's physical naming and no build inputs +/// (no verify ledger, generated files or routes): the input every page is built from. +pub fn view_of(ctx: &GenContext<'_>) -> Value { + docs_view::build_with_naming( + ctx.tree, + ctx.root, + None, + None, + None, + &NamingRegistry::builtin(), + &ctx.collection.physical_naming, + ) +} + +/// Whether the project chose a `meta migrate` dialect (`migrate.dialect`). +pub fn has_migrate(ctx: &GenContext<'_>) -> bool { + ctx.collection + .config + .migrate + .as_ref() + .is_some_and(|m| m.dialect.is_some()) +} + +/// Render one page from a template ref, naming the page when the template fails. +pub fn render_doc_page( + reference: &str, + data: &Value, + templates: &DocsTemplates, + path: &str, +) -> Result { + let request = RenderRequest::new(Body::Ref(reference), data, templates).format("markdown"); + render(&request).map_err(|e| { + GenError::new( + ERR_DOC_PAGE, + format!("failed rendering '{reference}' for '{path}': {e}"), + ) + }) +} + +/// `requirements.toon`: the ledger for tools. `None` for a model declaring no requirement. +pub fn requirements_toon_page( + view: &Value, + templates: &DocsTemplates, +) -> Result, GenError> { + let rows = requirement_rows(view); + if rows.is_empty() { + return Ok(None); + } + render_doc_page( + REQUIREMENTS_TOON_REF, + &requirements_toon_data(&rows), + templates, + "requirements.toon", + ) + .map(Some) +} + +/// `agent/requirements.md`. `None` for a model declaring no requirement. +pub fn agent_requirements_page( + view: &Value, + templates: &DocsTemplates, + path: &str, +) -> Result, GenError> { + let ledger = + |data: &Value| render_doc_page(REQUIREMENTS_PAGE_REF, data, templates, "requirements.md"); + match agent_requirements_page_data(view, ledger)? { + Some(data) => { + render_doc_page(AGENT_REQUIREMENTS_PAGE_REF, &data, templates, path).map(Some) + } + None => Ok(None), + } +} + +/// The model-only `agent/schema.md`. `None` for a model with no table and no view. +pub fn agent_schema_page( + view: &Value, + has_migrate: bool, + templates: &DocsTemplates, + path: &str, +) -> Result, GenError> { + match agent_schema_page_data(view, has_migrate) { + Some(data) => { + let page = render_doc_page(AGENT_SCHEMA_PAGE_REF, &data, templates, path)?; + Ok(Some(end_with_one_newline(&page))) + } + None => Ok(None), + } +} diff --git a/server/rust/metaobjects-codegen/src/docs_site.rs b/server/rust/metaobjects-codegen/src/docs_site.rs index 5f7d6e160d..6bdd8935df 100644 --- a/server/rust/metaobjects-codegen/src/docs_site.rs +++ b/server/rust/metaobjects-codegen/src/docs_site.rs @@ -243,12 +243,14 @@ impl Generator for DocsSite { } }; let manifest = files.map(|f| Value::Object(f.clone())); - let view = docs_view::build( + let view = docs_view::build_with_naming( ctx.tree, ctx.root, verify.as_ref(), manifest.as_ref(), routes.as_ref(), + &metaobjects::naming::NamingRegistry::builtin(), + &ctx.collection.physical_naming, ); let owned = project.join(OWNED_DOCS_SITE_DIR); let title = self.title.clone().unwrap_or_else(|| { diff --git a/server/rust/metaobjects-codegen/src/eject.rs b/server/rust/metaobjects-codegen/src/eject.rs index 259161acbc..af0affb8b2 100644 --- a/server/rust/metaobjects-codegen/src/eject.rs +++ b/server/rust/metaobjects-codegen/src/eject.rs @@ -251,6 +251,33 @@ pub const REFERENCES: &[Reference] = &[ (reads no model; templates/metamodel/ in the project wins)", source: include_str!("metamodel_docs.rs"), }, + Reference { + name: "requirements", + tier: "neutral", + opt_in: true, + package_only: false, + layer: "docs", + module: "requirements_docs", + type_name: "RequirementsGenerator", + needs: &[], + summary: "the requirement ledger as requirements.toon, for tools, read off the docs \ + view (templates/requirements/ in the project wins)", + source: include_str!("requirements_docs.rs"), + }, + Reference { + name: "agent-docs", + tier: "neutral", + opt_in: true, + package_only: false, + layer: "docs", + module: "agent_docs", + type_name: "AgentDocsGenerator", + needs: &[], + summary: "pages for a coding agent: agent/requirements.md (node index and ledger) and \ + the model-only agent/schema.md, read off the docs view (templates/agent/ in \ + the project wins; agent/ui.md stays TypeScript)", + source: include_str!("agent_docs.rs"), + }, Reference { name: "docs-site", tier: "neutral", diff --git a/server/rust/metaobjects-codegen/src/generator_list.rs b/server/rust/metaobjects-codegen/src/generator_list.rs index 9723b5fbe1..38cc9f64ca 100644 --- a/server/rust/metaobjects-codegen/src/generator_list.rs +++ b/server/rust/metaobjects-codegen/src/generator_list.rs @@ -14,7 +14,7 @@ //! ignored. Of the shipped generators only `metamodel-docs` takes one (`subDir`). The list carries no layer or set settings, //! because a layer is only a generator. A project with no such file runs every generator its host //! offers but the opt-in ones (the `service-routes` transport, which brings a web framework into -//! the build, and `metamodel-docs`, which writes reference pages no project asked for), which is +//! the build, and the docs generators `metamodel-docs`, `requirements` and `agent-docs`, which write pages no project asked for), which is //! what a project did before the file existed. A list may leave a generator //! out; generated files of a generator that left the list are swept like those of any //! generator that stops emitting them (an edited one is refused by name). @@ -246,12 +246,14 @@ mod tests { assert_eq!(all.len(), without_transport.len() + 1); assert_eq!(without_transport, names(&parse(&scaffold(false)).unwrap())); assert!(check(&all, &shipped_names()).is_ok()); - for docs in ["metamodel-docs", "docs-site"] { + for docs in ["metamodel-docs", "requirements", "agent-docs", "docs-site"] { assert!(!all.iter().any(|n| n == docs), "{docs}"); } assert!( !runs_unlisted("service-routes") && !runs_unlisted("metamodel-docs") + && !runs_unlisted("requirements") + && !runs_unlisted("agent-docs") && !runs_unlisted("docs-site") && runs_unlisted("entity") ); @@ -316,7 +318,7 @@ mod tests { let e = check(&s(&["entity", "nope"]), &available).unwrap_err(); assert!( e.contains("\"nope\"") - && e.contains("available: entity, rules-names, contract-types, repository, service, service-routes, client, commands, render-helper, output-parser, output-prompt, metamodel-docs"), + && e.contains("available: entity, rules-names, contract-types, repository, service, service-routes, client, commands, render-helper, output-parser, output-prompt, metamodel-docs, requirements, agent-docs"), "{e}" ); let e = check(&s(&["client"]), &available).unwrap_err(); diff --git a/server/rust/metaobjects-codegen/src/lib.rs b/server/rust/metaobjects-codegen/src/lib.rs index 5d4b11d5e6..0923f5db4d 100644 --- a/server/rust/metaobjects-codegen/src/lib.rs +++ b/server/rust/metaobjects-codegen/src/lib.rs @@ -18,9 +18,11 @@ // compiles here and as a project's owned copy (`cargo meta eject`). extern crate self as metaobjects_codegen; +pub mod agent_docs; pub mod client; pub mod commands; pub mod contract_types; +pub mod docs_pages; pub mod docs_site; pub mod eject; pub mod emitted; @@ -41,12 +43,14 @@ pub mod plan; pub mod project; pub mod render_helper; pub mod repository; +pub mod requirements_docs; pub mod rules_names; pub mod service; pub mod service_routes; pub mod sha256; pub mod writer; +pub use agent_docs::AgentDocsGenerator; pub use client::ClientGenerator; pub use commands::CommandsGenerator; pub use contract_types::ContractTypesGenerator; @@ -65,6 +69,7 @@ pub use output_parser::OutputParserGenerator; pub use output_prompt::OutputPromptGenerator; pub use render_helper::{RenderHelperGenerator, TemplateCheck, check_templates}; pub use repository::RepositoryGenerator; +pub use requirements_docs::RequirementsGenerator; pub use rules_names::RulesNamesGenerator; pub use service::ServiceGenerator; pub use service_routes::ServiceRoutesGenerator; @@ -84,6 +89,8 @@ pub fn shipped_generators() -> Vec> { Box::new(OutputParserGenerator), Box::new(OutputPromptGenerator), Box::new(MetamodelDocsGenerator), + Box::new(RequirementsGenerator), + Box::new(AgentDocsGenerator), Box::new(DocsSiteGenerator), ] } diff --git a/server/rust/metaobjects-codegen/src/metamodel_templates.rs b/server/rust/metaobjects-codegen/src/metamodel_templates.rs index 516a6bf401..b0500b0c9e 100644 --- a/server/rust/metaobjects-codegen/src/metamodel_templates.rs +++ b/server/rust/metaobjects-codegen/src/metamodel_templates.rs @@ -1,4 +1,4 @@ -//! The shipped templates of the `metamodel-docs` generator: the shared `templates/metamodel/` +//! The shipped templates of the `metamodel-docs`, `requirements` and `agent-docs` generators: the shared `templates/metamodel/` //! Mustache set every port renders, synced into this crate by `scripts/sync-doc-templates.sh` //! and embedded here, so an ejected copy of the generator (which cannot `include_str!` them //! from its own directory) reads them through [`shipped_template`]. @@ -8,6 +8,11 @@ use std::collections::BTreeMap; const INDEX: &str = include_str!("../templates/metamodel/index.md.mustache"); const PROVIDERS: &str = include_str!("../templates/metamodel/providers.md.mustache"); const TYPE_PAGE: &str = include_str!("../templates/metamodel/type-page.md.mustache"); +const REQUIREMENTS_MD: &str = include_str!("../templates/requirements/requirements.md.mustache"); +const REQUIREMENTS_TOON: &str = + include_str!("../templates/requirements/requirements.toon.mustache"); +const AGENT_REQUIREMENTS: &str = include_str!("../templates/agent/requirements.md.mustache"); +const AGENT_SCHEMA: &str = include_str!("../templates/agent/schema.md.mustache"); const PROVIDER_DESCRIPTIONS: &str = include_str!("../templates/metamodel/provider-descriptions.json"); @@ -17,6 +22,10 @@ pub fn shipped_template(reference: &str) -> Option<&'static str> { "metamodel/index.md" => Some(INDEX), "metamodel/providers.md" => Some(PROVIDERS), "metamodel/type-page.md" => Some(TYPE_PAGE), + "requirements/requirements.md" => Some(REQUIREMENTS_MD), + "requirements/requirements.toon" => Some(REQUIREMENTS_TOON), + "agent/requirements.md" => Some(AGENT_REQUIREMENTS), + "agent/schema.md" => Some(AGENT_SCHEMA), _ => None, } } diff --git a/server/rust/metaobjects-codegen/src/plan.rs b/server/rust/metaobjects-codegen/src/plan.rs index f85acbcb2d..250e416ce7 100644 --- a/server/rust/metaobjects-codegen/src/plan.rs +++ b/server/rust/metaobjects-codegen/src/plan.rs @@ -2103,3 +2103,10 @@ fn strongly_connected(adjacency: &[Vec]) -> Vec { // The shipped Mustache templates of the `metamodel-docs` generator, reached through the // engine surface so an owned copy of that generator reads them without a path into this crate. pub use crate::metamodel_templates::{shipped_provider_descriptions, shipped_template}; + +// The docs page builders of the `requirements` and `agent-docs` generators (rows, page data and +// the rendered pages, read off the docs view), reached through the same surface. +pub use crate::docs_pages::{ + DocsTemplates, agent_requirements_page, agent_schema_page, has_migrate, requirements_toon_page, + view_of, +}; diff --git a/server/rust/metaobjects-codegen/src/requirements_docs.rs b/server/rust/metaobjects-codegen/src/requirements_docs.rs new file mode 100644 index 0000000000..5a8bf9e2a0 --- /dev/null +++ b/server/rust/metaobjects-codegen/src/requirements_docs.rs @@ -0,0 +1,45 @@ +//! The `requirements` generator: the requirement ledger as `requirements.toon`, for tools. +//! People read the ledger in the explorer (`docs-site`); the human `requirements.md` page is +//! retired. +//! +//! The page is the shared `templates/requirements/requirements.toon.mustache`, rendered over +//! the rows read off the docs view (`metaobjects_codegen::plan`'s docs page builders). A model +//! declaring no `requirement.*` node gets no file. A project's own +//! `templates/requirements/requirements.toon.mustache` wins over the shipped one. + +use metaobjects_codegen::generator::{EmittedFile, GenContext, GenError, Generator}; +use metaobjects_codegen::plan::{DocsTemplates, requirements_toon_page, view_of}; + +/// Bump when the emitted text changes shape, so a stored skip key never survives it. +const FORMAT: u32 = 1; + +/// Where a project's own templates live, from the project root. +const TEMPLATE_DIR: &str = "templates/requirements"; +const TOON_FILE: &str = "requirements.toon"; + +/// The requirements generator. +#[derive(Debug, Clone, Copy, Default)] +pub struct RequirementsGenerator; + +impl Generator for RequirementsGenerator { + fn name(&self) -> &str { + "requirements" + } + + fn identity(&self) -> String { + format!("requirements:{FORMAT}") + } + + fn extra_inputs(&self) -> Vec { + vec![TEMPLATE_DIR.to_string()] + } + + fn generate(&self, ctx: &GenContext<'_>) -> Result, GenError> { + let templates = DocsTemplates::new(ctx); + let page = requirements_toon_page(&view_of(ctx), &templates)?; + Ok(page + .map(|text| EmittedFile::new(TOON_FILE, text)) + .into_iter() + .collect()) + } +} diff --git a/server/rust/metaobjects-codegen/tests/common/mod.rs b/server/rust/metaobjects-codegen/tests/common/mod.rs index 38f28dedf3..ca8c49825c 100644 --- a/server/rust/metaobjects-codegen/tests/common/mod.rs +++ b/server/rust/metaobjects-codegen/tests/common/mod.rs @@ -180,13 +180,19 @@ pub fn cargo(dir: &Path, args: &[&str]) -> std::process::Output { .expect("cargo runs") } -/// The shipped generators that write crates: every one but the two docs generators, -/// `metamodel-docs` and `docs-site`, whose pages are not a crate. Each is held to its own corpus -/// (`tests/metamodel_docs.rs`, `tests/docs_site.rs`). +/// The shipped generators that write crates: every one but the docs generators, +/// `metamodel-docs`, `requirements`, `agent-docs` and `docs-site`, whose pages are not a crate. +/// Each is held to its own corpus (`tests/metamodel_docs.rs`, `tests/docs_page_conformance.rs`, +/// `tests/docs_site.rs`). pub fn crate_generators() -> Vec> { shipped_generators() .into_iter() - .filter(|g| !matches!(g.name(), "metamodel-docs" | "docs-site")) + .filter(|g| { + !matches!( + g.name(), + "metamodel-docs" | "requirements" | "agent-docs" | "docs-site" + ) + }) .collect() } diff --git a/server/rust/metaobjects-codegen/tests/docs_page_conformance.rs b/server/rust/metaobjects-codegen/tests/docs_page_conformance.rs new file mode 100644 index 0000000000..77834016d6 --- /dev/null +++ b/server/rust/metaobjects-codegen/tests/docs_page_conformance.rs @@ -0,0 +1,181 @@ +//! The docs page corpus (`fixtures/docs-page-conformance/`): the pages every port writes from +//! its docs view, `requirements.toon`, `agent/requirements.md` and the model-only +//! `agent/schema.md`. Per case, in order: the rows the builders read off the view, the page data, +//! then the bytes the `requirements` and `agent-docs` generators write through the engine. The +//! set of pages is pinned too: a page the case does not list must not be written. + +mod common; + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use metaobjects::docs_view; +use metaobjects::loader::Loader; +use metaobjects::providers::{compose_registry, core_providers}; +use metaobjects_codegen::docs_pages::{ + REQUIREMENTS_PAGE_REF, agent_requirements_page_data, agent_schema_page_data, requirement_rows, + requirements_ledger_data, requirements_toon_data, schema_rows, +}; +use metaobjects_codegen::plan::shipped_template; +use metaobjects_codegen::render::{Body, Provider, RenderRequest, render}; +use serde_json::Value; + +fn corpus() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../fixtures/docs-page-conformance/cases") +} + +struct Shipped; +impl Provider for Shipped { + fn resolve(&self, reference: &str) -> Option { + shipped_template(reference).map(str::to_string) + } +} + +fn walk(dir: &Path, prefix: &str, out: &mut BTreeMap) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.map(Result::unwrap) { + let name = entry.file_name().to_string_lossy().to_string(); + if entry.path().is_dir() { + walk(&entry.path(), &format!("{prefix}{name}/"), out); + } else { + out.insert( + format!("{prefix}{name}"), + std::fs::read_to_string(entry.path()).unwrap(), + ); + } + } +} + +fn meta_files(input: &Path) -> Vec<(String, String)> { + let mut files: Vec<(String, String)> = std::fs::read_dir(input) + .unwrap() + .map(Result::unwrap) + .map(|e| e.file_name().to_string_lossy().to_string()) + .filter(|n| n.starts_with("meta.") && n.ends_with(".json")) + .map(|n| (n.clone(), std::fs::read_to_string(input.join(&n)).unwrap())) + .collect(); + files.sort(); + files +} + +fn json(text: &str) -> Value { + serde_json::from_str(text).unwrap() +} + +fn view_of_case(input: &Path) -> Value { + let mut registry = compose_registry(&core_providers()).unwrap(); + registry.seal(); + let loaded = Loader::new(®istry) + .strict(true) + .load_sources(&meta_files(input)); + assert!(loaded.errors.is_empty(), "{:?}", loaded.errors); + docs_view::build(&loaded.tree, loaded.root, None, None, None) +} + +fn page(reference: &str, data: &Value) -> String { + render(&RenderRequest::new(Body::Ref(reference), data, &Shipped).format("markdown")).unwrap() +} + +/// The rows and the page data, by path under `expected/`, as the builders make them. +fn built(view: &Value, has_migrate: bool) -> BTreeMap { + let mut out = BTreeMap::new(); + let rows = requirement_rows(view); + if !rows.is_empty() { + out.insert("rows/requirements.json".into(), Value::Array(rows.clone())); + out.insert( + "data/ledger.md.json".into(), + requirements_ledger_data(&rows, true), + ); + out.insert( + "data/requirements.toon.json".into(), + requirements_toon_data(&rows), + ); + } + let ledger = |d: &Value| Ok::<_, String>(page(REQUIREMENTS_PAGE_REF, d)); + if let Some(d) = agent_requirements_page_data(view, ledger).unwrap() { + out.insert("data/agent-requirements.md.json".into(), d); + } + if let Some(d) = agent_schema_page_data(view, has_migrate) { + out.insert("data/agent-schema.md.json".into(), d); + out.insert("rows/schema.json".into(), schema_rows(view)); + } + out +} + +#[test] +fn every_case_reproduces_its_rows_data_and_pages() { + let mut cases: Vec = std::fs::read_dir(corpus()) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.is_dir()) + .collect(); + cases.sort(); + assert!(cases.len() >= 4, "the corpus has its cases: {cases:?}"); + let mut failures = Vec::new(); + for case in &cases { + let name = case.file_name().unwrap().to_string_lossy().to_string(); + let input = case.join("input"); + let config = std::fs::read_to_string(input.join(".metaobjects/config.json")).ok(); + let has_migrate = config + .as_deref() + .is_some_and(|c| json(c)["migrate"]["dialect"].is_string()); + let mut expected = BTreeMap::new(); + walk(&case.join("expected"), "", &mut expected); + + // 1 and 2: rows, then page data, as JSON values. + let view = view_of_case(&input); + let built = built(&view, has_migrate); + for (path, value) in &built { + match expected.get(path) { + Some(text) if json(text) == *value => {} + Some(_) => failures.push(format!("{name}: {path} differs")), + None => failures.push(format!("{name}: {path} is built but not expected")), + } + } + for path in expected.keys().filter(|p| p.ends_with(".json")) { + if !built.contains_key(path) { + failures.push(format!("{name}: {path} is expected but not built")); + } + } + + // 3: the bytes the generators write, through the engine. + let p = common::Scratch::project("docs-page", &[]); + for (file, text) in meta_files(&input) { + p.write(&format!("metaobjects/{file}"), &text); + } + if let Some(c) = &config { + // The corpus config carries only the setting a case sets; this port's config reader + // also wants the `schema_version` every real config has. + let mut c = json(c); + c["schema_version"] = 1.into(); + p.write(".metaobjects/config.json", &c.to_string()); + } + p.write( + "metaobjects.config.json", + r#"{ "generators": ["requirements", "agent-docs"] }"#, + ); + let mut opts = metaobjects_codegen::RunOptions::new(p.path()); + opts.out_dir = PathBuf::from("generated"); + metaobjects_codegen::run(&opts, &metaobjects_codegen::shipped_generators()) + .unwrap_or_else(|e| panic!("{name}: gen failed: {e}")); + let mut written = BTreeMap::new(); + walk(&p.path().join("generated"), "", &mut written); + let pages: BTreeMap<&String, &String> = expected + .iter() + .filter(|(k, _)| !k.starts_with("data/") && !k.starts_with("rows/")) + .collect(); + let got: Vec<&String> = written.keys().collect(); + let want: Vec<&String> = pages.keys().copied().collect(); + if got != want { + failures.push(format!("{name}: pages written {got:?}, expected {want:?}")); + } + for (path, text) in pages { + if written.get(path) != Some(text) { + failures.push(format!("{name}: {path} bytes differ")); + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/server/rust/metaobjects-codegen/tests/docs_site.rs b/server/rust/metaobjects-codegen/tests/docs_site.rs index 74ff678152..20fdc780ba 100644 --- a/server/rust/metaobjects-codegen/tests/docs_site.rs +++ b/server/rust/metaobjects-codegen/tests/docs_site.rs @@ -49,14 +49,14 @@ fn the_model_script_is_typescripts_bytes() { // The title carries U+2028, which JSON.stringify leaves unescaped. // explorerModelScript({ title: "Shop \u2028", footer: "v1", texts, templates, view }) in // @metaobjectsdev/docs-site, over the same shop view, gives this stamp and these bytes. - assert_eq!(stamp, "05b57283a47416e2"); + assert_eq!(stamp, "33fd741544d5a480"); assert_eq!( sha256_hex(script.as_bytes()), - "02f2d4321101c0ab9fa9e22db542ff8f71f1e952748e8f894d388bd43feeb6bc" + "c649aa99ef4c570149d6ce06f102738524db766915829a889b39f884af061070" ); assert_eq!( metaobjects::docs_view::stamp_script(&stamp), - "window.MO_STAMP = \"05b57283a47416e2\";\n" + "window.MO_STAMP = \"33fd741544d5a480\";\n" ); } diff --git a/server/rust/metaobjects/src/docs_view.rs b/server/rust/metaobjects/src/docs_view.rs index e8e90b5578..624902c4b5 100644 --- a/server/rust/metaobjects/src/docs_view.rs +++ b/server/rust/metaobjects/src/docs_view.rs @@ -20,6 +20,7 @@ use serde_json::{Map, Value, json}; use crate::json::{js_quote, to_js_compact, to_js_pretty}; use crate::loader::{is_ref_bearing_attr, reference_targets, split_child_tail}; +use crate::naming::{NamingRegistry, PhysicalNaming}; use crate::node::{NodeId, PACKAGE_SEP, Tree}; use crate::parser::TYPE_OBJECT; use crate::serializer::normalize; @@ -113,9 +114,33 @@ pub fn build( manifest: Option<&Value>, routes: Option<&Value>, ) -> Value { - Build::new(tree, root).run(verify, manifest, routes) + build_with_naming( + tree, + root, + verify, + manifest, + routes, + &NamingRegistry::builtin(), + &PhysicalNaming::default(), + ) +} + +/// [`build`] with the project's physical naming (the `naming` block of +/// `.metaobjects/config.json`), which names the tables and columns of the `storage` section. +pub fn build_with_naming( + tree: &Tree, + root: NodeId, + verify: Option<&Value>, + manifest: Option<&Value>, + routes: Option<&Value>, + registry: &NamingRegistry, + naming: &PhysicalNaming, +) -> Value { + Build::new(tree, root, registry, naming).run(verify, manifest, routes) } +mod storage; + // ---- the walk ------------------------------------------------------------------------------ /// A node as walked: where it sits, and the ids and pages it gets. Indexes are into @@ -149,6 +174,8 @@ struct Ledger { } struct Build<'t> { + registry: &'t NamingRegistry, + naming: &'t PhysicalNaming, tree: &'t Tree, root: NodeId, objects: ObjectIndex, @@ -161,8 +188,15 @@ struct Build<'t> { } impl<'t> Build<'t> { - fn new(tree: &'t Tree, root: NodeId) -> Self { + fn new( + tree: &'t Tree, + root: NodeId, + registry: &'t NamingRegistry, + naming: &'t PhysicalNaming, + ) -> Self { let mut b = Self { + registry, + naming, tree, root, objects: ObjectIndex::build(tree, root), @@ -886,6 +920,7 @@ impl<'t> Build<'t> { "requirements": reqs, "advisories": advisories, "slices": slices, + "storage": self.storage(), }) } diff --git a/server/rust/metaobjects/src/docs_view/storage.rs b/server/rust/metaobjects/src/docs_view/storage.rs new file mode 100644 index 0000000000..20aa81f312 --- /dev/null +++ b/server/rust/metaobjects/src/docs_view/storage.rs @@ -0,0 +1,583 @@ +//! The docs view's `storage` section: the tables and views the model declares, named by the +//! port's own naming helpers (`docs/features/docs-view.md`, "storage"). +//! +//! Model-only, as TypeScript's `buildStorage` (`docs-view/storage.ts`) is when it has no +//! expected schema: a table per concrete object whose primary source is a writable, managed +//! table (abstract bases and sourceless values have none; a TPH subtype shares its base's +//! table and adds its own columns after the base's, nullable), a view per object whose primary +//! source is a view. The physical facts (SQL type, default, indexes, checks, constraint names, +//! referential actions) are `null` here: only the TypeScript run fills them. + +use std::cmp::Ordering; +use std::collections::{HashMap, HashSet}; + +use serde_json::{Value, json}; + +use super::{ATTR_DESCRIPTION, Build, DOT, TYPE_FIELD, str_attr}; +use crate::loader::split_child_tail; +use crate::naming::{ + NamingCtx, primary_rdb_source, resolve_column_name, resolve_flattened_column_name, + source_effective_kind, source_is_read_only, source_physical_name, +}; +use crate::node::NodeId; +use crate::parser::TYPE_OBJECT; + +const TYPE_IDENTITY: &str = "identity"; +const TYPE_ORIGIN: &str = "origin"; +const TYPE_VALIDATOR: &str = "validator"; +const TYPE_SOURCE: &str = "source"; +const SUBTYPE_PRIMARY: &str = "primary"; +const SUBTYPE_REFERENCE: &str = "reference"; +const SUBTYPE_REQUIRED: &str = "required"; +const SUBTYPE_OBJECT: &str = "object"; +const KIND_VIEW: &str = "view"; +const ATTR_DISCRIMINATOR: &str = "discriminator"; +const ATTR_DISCRIMINATOR_VALUE: &str = "discriminatorValue"; +const ATTR_OBJECT_REF: &str = "objectRef"; +const ATTR_REQUIRED: &str = "required"; +const ATTR_STORAGE: &str = "storage"; +const ATTR_SCHEMA: &str = "schema"; +const ATTR_UNMANAGED: &str = "unmanaged"; +const ATTR_FIELDS: &str = "fields"; +const ATTR_GENERATION: &str = "generation"; +const ATTR_ENFORCE: &str = "enforce"; +const ATTR_REFERENCES: &str = "references"; +const STORAGE_FLATTENED: &str = "flattened"; +const GENERATION_INCREMENT: &str = "increment"; +const GENERATION_UUID: &str = "uuid"; + +/// A column before its field is linked. +struct RawColumn { + name: String, + nullable: bool, + identity: String, + description: String, +} + +/// The field behind a column: its owner object and the field node. +type Mapping = (NodeId, NodeId); + +/// A foreign key, before it is written as JSON. +#[derive(PartialEq, Eq)] +struct Fk { + columns: Vec, + ref_table: String, + ref_columns: Vec, +} + +/// JavaScript's string order: by UTF-16 code unit. +fn by_code_unit(a: &str, b: &str) -> Ordering { + a.encode_utf16().cmp(b.encode_utf16()) +} + +fn key(name: &str, schema: &str) -> String { + if schema.is_empty() { + name.to_string() + } else { + format!("{schema}.{name}") + } +} + +impl Build<'_> { + fn ctx(&self) -> NamingCtx<'_> { + NamingCtx::new(self.registry, self.naming) + } + + fn column_name(&self, field: NodeId) -> String { + resolve_column_name(self.tree, field, &self.ctx()) + .unwrap_or_else(|_| self.tree.node(field).name.clone()) + } + + /// The column of the object's field `name`, or `name` through the column strategy. + fn column_of(&self, obj: NodeId, name: &str) -> String { + match self.find_field(obj, name) { + Some(f) => self.column_name(f), + None => self + .registry + .apply_column_naming_strategy(name, &self.naming.columns) + .unwrap_or_else(|_| name.to_string()), + } + } + + fn fields_of(&self, obj: NodeId) -> Vec { + self.tree + .children(obj) + .iter() + .copied() + .filter(|&c| self.tree.node(c).type_name == TYPE_FIELD) + .collect() + } + + fn find_field(&self, obj: NodeId, name: &str) -> Option { + self.fields_of(obj) + .into_iter() + .find(|&f| self.tree.node(f).name == name) + } + + fn is_required(&self, field: NodeId) -> bool { + // ADR-0039: resolving. @required and validator.required may be inherited via extends. + if self.tree.attr(field, ATTR_REQUIRED) == Some(&Value::Bool(true)) { + return true; + } + self.tree.children(field).iter().any(|&c| { + let n = self.tree.node(c); + n.type_name == TYPE_VALIDATOR && n.sub_type == SUBTYPE_REQUIRED + }) + } + + fn is_derived(&self, field: NodeId) -> bool { + // ADR-0039 own (category 4): origin.* never inherits (ADR-0029). + self.tree + .own_children(field) + .iter() + .any(|&c| self.tree.node(c).type_name == TYPE_ORIGIN) + } + + /// The `@discriminator`-bearing ANCESTOR of `entity`. + fn discriminator_base(&self, entity: NodeId) -> Option { + let mut seen = vec![entity]; + let mut cur = self.tree.node(entity).super_node; + while let Some(a) = cur { + if seen.contains(&a) { + break; + } + seen.push(a); + // ADR-0039 sanctioned own: an explicit super-resolution walk reads each ancestor's + // own attr. + if self + .tree + .own_attr(a, ATTR_DISCRIMINATOR) + .is_some_and(|x| !x.value.is_null()) + { + return Some(a); + } + cur = self.tree.node(a).super_node; + } + None + } + + fn is_tph_subtype(&self, entity: NodeId) -> bool { + self.tree.attr(entity, ATTR_DISCRIMINATOR_VALUE).is_some() + && self.discriminator_base(entity).is_some() + } + + fn tph_concrete_subtypes(&self, base: NodeId, objects: &[NodeId]) -> Vec { + if self.tree.attr(base, ATTR_DISCRIMINATOR).is_none() { + return Vec::new(); + } + objects + .iter() + .copied() + .filter(|&o| { + !super::is_abstract(self.tree, o) + && self.tree.attr(o, ATTR_DISCRIMINATOR_VALUE).is_some() + && self.discriminator_base(o) == Some(base) + }) + .collect() + } + + fn identity_fields(&self, identity: NodeId) -> Vec { + match self.tree.attr(identity, ATTR_FIELDS) { + Some(Value::String(s)) => s + .split(',') + .map(str::trim) + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect(), + Some(Value::Array(items)) => items.iter().map(crate::json::js_display).collect(), + _ => Vec::new(), + } + } + + fn primary_identity(&self, obj: NodeId) -> Option { + self.tree.children(obj).iter().copied().find(|&c| { + let n = self.tree.node(c); + n.type_name == TYPE_IDENTITY && n.sub_type == SUBTYPE_PRIMARY + }) + } + + fn is_flattened(&self, field: NodeId) -> bool { + self.tree.node(field).sub_type == SUBTYPE_OBJECT + && self.tree.attr(field, ATTR_STORAGE).and_then(Value::as_str) + == Some(STORAGE_FLATTENED) + } + + /// The object a reference attribute resolved to (`refTarget`): none for a list value. + fn ref_target(&self, n: NodeId, attr: &str) -> Option { + if !matches!(self.tree.attr(n, attr), Some(Value::String(_))) { + return None; + } + let target = self.declaring_targets(n, attr).first().copied().flatten()?; + (self.tree.node(target).type_name == TYPE_OBJECT).then_some(target) + } + + fn raw_column(&self, field: NodeId, is_pk: bool, generation: &str, name: String) -> RawColumn { + RawColumn { + name, + nullable: !is_pk && !self.is_required(field), + identity: if is_pk + && (generation == GENERATION_INCREMENT || generation == GENERATION_UUID) + { + generation.to_string() + } else { + String::new() + }, + description: str_attr(self.tree, field, ATTR_DESCRIPTION), + } + } + + fn field_columns(&self, field: NodeId, is_pk: bool, generation: &str) -> Vec { + if self.is_flattened(field) { + let Some(target) = self.ref_target(field, ATTR_OBJECT_REF) else { + return Vec::new(); + }; + return self + .fields_of(target) + .into_iter() + .map(|nested| { + let name = resolve_flattened_column_name(self.tree, field, nested, &self.ctx()) + .unwrap_or_else(|_| self.tree.node(nested).name.clone()); + self.raw_column(nested, false, "", name) + }) + .collect(); + } + vec![self.raw_column(field, is_pk, generation, self.column_name(field))] + } + + /// The referenced key's columns: an explicit dotted tail on `@references`, else the + /// target's primary identity (its first field), else `id`. + fn target_columns(&self, reference: NodeId, target: NodeId) -> Vec { + let tail = match self.tree.attr(reference, ATTR_REFERENCES) { + Some(Value::String(raw)) => split_child_tail(raw).1.to_string(), + _ => String::new(), + }; + let tail = tail.strip_prefix(DOT).unwrap_or(&tail); + let mut names: Vec = tail + .split(',') + .map(str::trim) + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect(); + if names.is_empty() { + let pk = self + .primary_identity(target) + .map(|i| self.identity_fields(i)) + .unwrap_or_default(); + names = vec![pk.into_iter().next().unwrap_or_else(|| "id".to_string())]; + } + names.iter().map(|n| self.column_of(target, n)).collect() + } + + fn foreign_keys( + &self, + entity: NodeId, + objects: &[NodeId], + table_of: &HashMap, + ) -> Vec { + let is_ref = |c: NodeId| { + let n = self.tree.node(c); + n.type_name == TYPE_IDENTITY && n.sub_type == SUBTYPE_REFERENCE + }; + let mut refs: Vec<(NodeId, NodeId)> = self + .tree + .children(entity) + .iter() + .copied() + .filter(|&c| is_ref(c)) + .map(|c| (entity, c)) + .collect(); + if self.tree.attr(entity, ATTR_DISCRIMINATOR).is_some() { + let base_names: HashSet = refs + .iter() + .map(|&(_, r)| self.tree.node(r).name.clone()) + .collect(); + for sub in self.tph_concrete_subtypes(entity, objects) { + for &c in self.tree.children(sub).iter() { + if is_ref(c) && !base_names.contains(&self.tree.node(c).name) { + refs.push((sub, c)); + } + } + } + } + let mut fks: Vec = Vec::new(); + for (holder, reference) in refs { + // A logical-only reference is no constraint. + if self.tree.attr(reference, ATTR_ENFORCE) == Some(&Value::Bool(false)) { + continue; + } + let Some(target) = self.ref_target(reference, ATTR_REFERENCES) else { + continue; + }; + let Some(ref_table) = table_of.get(&target).filter(|t| !t.is_empty()) else { + continue; + }; + let names = self.identity_fields(reference); + if names.is_empty() { + continue; + } + let fk = Fk { + columns: names.iter().map(|n| self.column_of(holder, n)).collect(), + ref_table: ref_table.clone(), + ref_columns: self.target_columns(reference, target), + }; + // Two subtypes may declare the same column: one constraint. + if !fks.contains(&fk) { + fks.push(fk); + } + } + fks + } + + /// The link to `field` as a member of the top-level `owner`: its own row of an inherited + /// one, or null. + fn member_link(&self, owner: NodeId, field: NodeId) -> Value { + let row = self.canonical.get(&owner).and_then(|&top| { + self.walked[top] + .children + .iter() + .copied() + .find(|&c| self.walked[c].node == field) + }); + row.map_or(Value::Null, |w| self.link(w)) + } + + fn object_link(&self, obj: NodeId) -> Value { + self.link_to(Some(obj), &self.tree.node(obj).name) + } + + fn schema_of(&self, source: NodeId) -> String { + str_attr(self.tree, source, ATTR_SCHEMA) + } + + pub(super) fn storage(&self) -> Value { + let tree = self.tree; + let ctx = self.ctx(); + let objects: Vec = tree + .children(self.root) + .iter() + .copied() + .filter(|&c| tree.node(c).type_name == TYPE_OBJECT) + .collect(); + let primary = |o: NodeId| primary_rdb_source(tree, o, &ctx).ok().flatten(); + let name_of = |s: NodeId| source_physical_name(tree, s, &ctx).unwrap_or_default(); + + // Pass 1: which objects own a table, and which are only a foreign-key target. + let mut entities: Vec<(NodeId, NodeId)> = Vec::new(); + let mut target_only: Vec<(NodeId, NodeId)> = Vec::new(); + let mut tph_members: Vec<(NodeId, NodeId)> = Vec::new(); + let is_writable_source = + |c: NodeId| tree.node(c).type_name == TYPE_SOURCE && !source_is_read_only(tree, c); + for &obj in &objects { + let base = self.discriminator_base(obj); + if let Some(base) = base + && (super::is_abstract(tree, obj) || self.is_tph_subtype(obj)) + { + tph_members.push((obj, base)); + continue; + } + if super::is_abstract(tree, obj) { + continue; + } + if !tree.children(obj).iter().any(|&c| is_writable_source(c)) { + continue; + } + let Some(source) = primary(obj) else { + continue; + }; + // ADR-0039 sanctioned own: @unmanaged is read off the object's OWN writable source. + let own = tree + .own_children(obj) + .iter() + .copied() + .find(|&c| is_writable_source(c)); + if own.is_some_and(|o| tree.attr(o, ATTR_UNMANAGED) == Some(&Value::Bool(true))) { + target_only.push((obj, source)); + continue; + } + entities.push((obj, source)); + } + let mut table_of: HashMap = entities + .iter() + .chain(target_only.iter()) + .map(|&(o, s)| (o, name_of(s))) + .collect(); + for &(member, base) in &tph_members { + if let Some(name) = table_of.get(&base).cloned() + && !table_of.contains_key(&member) + { + table_of.insert(member, name); + } + } + + // Every object at each storage key, in declaration order. + let mut at_key: HashMap> = HashMap::new(); + for &obj in &objects { + if let Some(source) = primary(obj) { + at_key + .entry(key(&name_of(source), &self.schema_of(source))) + .or_default() + .push(obj); + } + } + // The column to declaring field map: the first writer wins on a shared table. + let field_of = |k: &str| -> Vec<(String, Mapping)> { + let mut out: Vec<(String, Mapping)> = Vec::new(); + let mut seen: HashSet = HashSet::new(); + for &obj in at_key.get(k).into_iter().flatten() { + for field in self.fields_of(obj) { + let column = self.column_name(field); + if seen.insert(column.clone()) { + out.push((column, (obj, field))); + } + } + } + out + }; + let concrete_links = |k: &str| -> Vec { + at_key + .get(k) + .into_iter() + .flatten() + .filter(|&&o| !super::is_abstract(tree, o)) + .map(|&o| self.object_link(o)) + .collect() + }; + + let mut tables: Vec<(String, Value)> = Vec::new(); + let mut keys: HashSet = HashSet::new(); + for &(entity, source) in &entities { + let identity = self.primary_identity(entity); + let pk_names = identity + .map(|i| self.identity_fields(i)) + .unwrap_or_default(); + let generation = identity + .and_then(|i| tree.attr(i, ATTR_GENERATION)) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + let mut raw: Vec = Vec::new(); + for field in self.fields_of(entity) { + if self.is_derived(field) { + continue; + } + let is_pk = pk_names.contains(&tree.node(field).name); + raw.extend(self.field_columns(field, is_pk, if is_pk { &generation } else { "" })); + } + if tree.attr(entity, ATTR_DISCRIMINATOR).is_some() { + let mut existing: HashSet = raw.iter().map(|c| c.name.clone()).collect(); + let base_fields: HashSet = self + .fields_of(entity) + .iter() + .map(|&f| tree.node(f).name.clone()) + .collect(); + for sub in self.tph_concrete_subtypes(entity, &objects) { + for field in self.fields_of(sub) { + if base_fields.contains(&tree.node(field).name) || self.is_derived(field) { + continue; + } + let mut col = self.raw_column(field, false, "", self.column_name(field)); + if existing.contains(&col.name) { + continue; + } + // A row of any other subtype stores NULL here. + col.nullable = true; + existing.insert(col.name.clone()); + raw.push(col); + } + } + } + let schema = self.schema_of(source); + let name = name_of(source); + let k = key(&name, &schema); + let mapping: HashMap = field_of(&k).into_iter().collect(); + let columns: Vec = raw + .iter() + .map(|c| { + json!({ + "name": c.name, + "field": mapping + .get(&c.name) + .map_or(Value::Null, |&(o, f)| self.member_link(o, f)), + "nullable": c.nullable, + "identity": c.identity, + "description": c.description, + "sqlType": Value::Null, + "default": Value::Null, + }) + }) + .collect(); + let fks: Vec = self + .foreign_keys(entity, &objects, &table_of) + .into_iter() + .map(|f| { + json!({ + "columns": f.columns, + "refTable": f.ref_table, + "refColumns": f.ref_columns, + "name": Value::Null, + "onDelete": Value::Null, + "onUpdate": Value::Null, + }) + }) + .collect(); + tables.push(( + name.clone(), + json!({ + "name": name, + "schema": schema, + "declaredBy": self.object_link(entity), + "objects": concrete_links(&k), + "description": str_attr(tree, entity, ATTR_DESCRIPTION), + "primaryKey": pk_names.iter().map(|n| self.column_of(entity, n)).collect::>(), + "columns": columns, + "foreignKeys": fks, + "indexes": Value::Null, + "checks": Value::Null, + }), + )); + keys.insert(k); + } + + let mut views: Vec<(String, Value)> = Vec::new(); + for &obj in &objects { + if super::is_abstract(tree, obj) { + continue; + } + let Some(source) = primary(obj) else { + continue; + }; + if source_effective_kind(tree, source) != KIND_VIEW { + continue; + } + let schema = self.schema_of(source); + let name = name_of(source); + let k = key(&name, &schema); + if !keys.insert(k.clone()) { + continue; + } + let columns: Vec = field_of(&k) + .into_iter() + .map(|(n, (o, f))| json!({ "name": n, "field": self.member_link(o, f) })) + .collect(); + views.push(( + name.clone(), + json!({ + "name": name, + "schema": schema, + "declaredBy": self.object_link(obj), + "objects": concrete_links(&k), + "columns": columns, + }), + )); + } + + tables.sort_by(|a, b| by_code_unit(&a.0, &b.0)); + views.sort_by(|a, b| by_code_unit(&a.0, &b.0)); + json!({ + "physical": false, + "dialect": "", + "tables": tables.into_iter().map(|t| t.1).collect::>(), + "views": views.into_iter().map(|t| t.1).collect::>(), + }) + } +} diff --git a/server/rust/metaobjects/tests/docs_view_conformance.rs b/server/rust/metaobjects/tests/docs_view_conformance.rs index 420731e69d..f38623a369 100644 --- a/server/rust/metaobjects/tests/docs_view_conformance.rs +++ b/server/rust/metaobjects/tests/docs_view_conformance.rs @@ -112,8 +112,8 @@ fn the_docs_route_serves_the_model_alone_view() { std::fs::read_to_string(dir.join("expected.json")).unwrap() ); // metaDocsEtag(body) in @metaobjectsdev/runtime-ts over the same bytes. - assert_eq!(d.etag, "\"4c8c-0068e2ba\""); - assert!(d.matches(Some("\"4c8c-0068e2ba\""))); + assert_eq!(d.etag, "\"5c90-d00d12d4\""); + assert!(d.matches(Some("\"5c90-d00d12d4\""))); assert_eq!(META_DOCS_ROUTE_PATH, format!("{META_ROUTE_PATH}/docs")); assert!(meta_json(&loaded.tree, loaded.root).starts_with('{')); } From 04ad416ac3619bf902c527ccfddd2392429679c8 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 07:40:31 -0500 Subject: [PATCH 11/21] docs: agent pages in every port (CONFORMANCE, cli, changelog); Java pages honour the ledger, C# drops its scope-only filter --- AGENTS.md | 2 +- changelog.d/agent-pages-every-port.md | 6 ++- docs/CONFORMANCE.md | 43 +++++++++++++------ docs/features/cli.md | 8 ++++ fixtures/docs-page-conformance/README.md | 2 +- .../MetaObjects.Codegen/Docs/DocsViewPages.cs | 14 +++--- .../Generators/AgentDocsGenerator.cs | 4 +- .../generator/AgentDocsGenerator.java | 2 +- .../generator/RequirementsGenerator.java | 11 ++++- 9 files changed, 62 insertions(+), 30 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4c07da5621..863dda487f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,7 +74,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (laid out by `KotlinWriter`, ADR-0063, on the JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (584 fixtures; 48 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (584 fixtures; 49 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / Java / Kotlin / Python byte-identical; C# and Rust each carry a `KnownDrift` render ledger, recorded in `docs/CONFORMANCE.md`. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python; `op: guardedUpdate` is TS-only until each port's 1.3.0 guarded update lands), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (the Node reference helper writes them; a native tool is equally first-class, ADR-0015 Amendment 2). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/changelog.d/agent-pages-every-port.md b/changelog.d/agent-pages-every-port.md index 46f472786c..c629306c2b 100644 --- a/changelog.d/agent-pages-every-port.md +++ b/changelog.d/agent-pages-every-port.md @@ -5,7 +5,8 @@ `templates/requirements/` and `templates/agent/` Mustache pages, byte for byte what `fixtures/docs-page-conformance/` pins. A TypeScript project with no dialect now gets the model-only `agent/schema.md` too (it used to get no schema page); with a dialect it keeps the - physical page. `agent/ui.md` stays TypeScript's. + physical page. `agent/ui.md` stays TypeScript's. Rust has no requirement ledger of its own + yet, so its pages list every requirement the view carries, an uninherited import's included. The docs view gains a `storage` section (`docs/features/docs-view.md`): every table and view the model stores into, its columns (names from the port's naming helpers, each linked to its @@ -19,7 +20,8 @@ `requirements.md`; delete the committed copy (and its `.hashes/` entry goes with the run). **The always-on agent file points at the agent pages, only when they exist.** `meta init` - (and `--refresh-docs`) and the C#, Java and Python agent-docs commands now add a "Pages + (and `--refresh-docs`), `meta agent-docs` (which the C# and Java commands hand off to) and + Python's `metaobjects agent-docs` now add a "Pages generated for this project" section to `.metaobjects/AGENTS.md`, naming each agent page the project's last `gen` wrote (read from the committed `.metaobjects/.gen-state/.hashes/`) and when to read it. A project that wires none of them gets the file unchanged. Refresh the agent diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 2ae59a0255..83a2d1a6e8 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -1,6 +1,6 @@ # Conformance coverage -The MetaObjects standard ships **48 shared conformance corpora** under +The MetaObjects standard ships **49 shared conformance corpora** under [`fixtures/`](../fixtures/). Every port runs every corpus that is *applicable to it* and asserts the same expected behaviour against the same fixtures. **This page is the inverse index**: fixture → feature doc + per-port pass status, and it is the @@ -54,8 +54,9 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/dependency-conformance/`](../fixtures/dependency-conformance/) | 47 cases (36 resolution, 7 of them with a ledger arm, + 11 check) + 32 transport cases | ✓ (reference implementation; all four arms) | ✓ (resolution arm, all 36, ledger included; check arm, all 11) | inherits via Java | ✓ (resolution arm, all 36, ledger included; check arm, all 11, as `verify --deps`) | ✓ (resolution arm, all 36 identically, ledger included; check arm, all 11, as `deps check` and `verify --deps`; the transport arm is Node-only) | — | | [`fixtures/shared-model-conformance/`](../fixtures/shared-model-conformance/) | 15 cases (9 publish + 6 refusal) | ✓ (reference implementation) | ✓ (all 15; `SharedModelConformanceTest`) | inherits via Java (`KotlinSharedModelGeneratorTest` pins the generator) | ✓ (all 15; `SharedModelConformanceTests`) | ✓ (all 15; `test_shared_model_conformance.py`) | — | | [`fixtures/agent-context-conformance/`](../fixtures/agent-context-conformance/) | 6 | ✓ (the emitter is TS-owned) | — | — | — | — | — | +| [`fixtures/agent-pages-pointer/`](../fixtures/agent-pages-pointer/) (the always-on agent file names the agent pages the last `gen` wrote, from the committed `.hashes/`) | 3 cases | ✓ (reference) | — (`metaobjects:agent-docs` runs the Node CLI) | — | — (`dotnet meta agent-docs` runs the Node CLI) | ✓ | — (no agent-context scaffold) | | [`fixtures/list-query-conformance/`](../fixtures/list-query-conformance/) (how a list route reads its query string: filter tree, search, sort, page, or the named 400) | 95 cases | ✓ (reference; the source of the expected answers) | planned (R-JV) | planned (R-KT) | ✓ (`ListQueryConformanceTests`) | planned (R-PY) | ✓ (`list_query_conformance.rs`, the parser `meta_http` ships) | -| [`fixtures/docs-page-conformance/`](../fixtures/docs-page-conformance/) (the requirements pages and the model-only schema page: each page's data and bytes) | 4 cases | ✓ (reference; the source of the expected bytes) | planned | planned (through Java) | ✓ | planned | planned (G-RS-1) | +| [`fixtures/docs-page-conformance/`](../fixtures/docs-page-conformance/) (the requirement pages and the model-only schema page, built from the docs view: each page's rows, data and bytes) | 4 cases | ✓ (reference; the source of the expected bytes) | ✓ (`DocsPageConformanceTest`) | ✓ (through Java: the Kotlin generators call the JVM page builder) | ✓ | ✓ | ✓ (rows from the view; no requirement ledger, RS-V2) | | [`fixtures/metamodel-docs/`](../fixtures/metamodel-docs/) (the vocabulary reference pages: each page's data and bytes, shared `templates/metamodel/`) | 1 (23 pages) | ✓ (reference; the source of the expected bytes) | ✓ (`MetamodelDocsCorpusTest`) | ✓ (through Java's builder and emitter) | ✓ (`MetamodelDocsTests`) | ✓ (`test_metamodel_docs_conformance.py`) | ✓ (`tests/metamodel_docs.rs`) | | [`fixtures/fmt-conformance/`](../fixtures/fmt-conformance/) (#304 — `meta fmt`) | 13 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | — (no `fmt`) | | [`fixtures/field-lint-conformance/`](../fixtures/field-lint-conformance/) (the `verify` field authoring lint) | 15 | ✓ (reference) | ✓ | inherits via Java | ✓ | ✓ | — | @@ -108,7 +109,7 @@ the contracts and the conformance corpora this repository runs against every por `jinja-render-conformance/` and `jinja-verify-conformance/` (the Jinja engine and its payload check, Python and TypeScript only, ADR-0061), `persistence-conformance/` (runtime reads and writes, and the migration scenarios of - the TypeScript reference helper), `agent-context-conformance/`, `metamodel-docs/`, `fmt-conformance/` + the TypeScript reference helper), `agent-context-conformance/`, `agent-pages-pointer/`, `metamodel-docs/`, `fmt-conformance/` (the canonical serializer, surfaced per-file — ADR-0034's "canonical format" is core), `field-lint-conformance/` (the advisory field lint every port's `verify` prints), `model-lint-conformance/` (the advisory overlay, node-name and deprecated-reference lints), @@ -833,16 +834,32 @@ REST-standard work lands, and each port's change flips its own entry. The decisi All 4 cases → [features/requirements.md](features/requirements.md) (the documentation surfaces) and [features/templates-and-payloads.md](features/templates-and-payloads.md) (the shared templates). Each case is a model under `input/` and, under `expected/`, every page it -yields (`requirements.md`, `requirements.toon`, `agent/requirements.md`, the model-only -`agent/schema.md`) plus the data each page's shared template is fed and, under `rows/`, the -ledger and model-only schema rows that data is built from (the shapes the docs site reuses). The TypeScript -builders are the source of the expected bytes. The corpus README writes down what a -non-TypeScript schema page contains and what it leaves out. - -**Held to it:** `server/typescript/packages/cli/test/docs-page-conformance.test.ts` and -`server/python/tests/conformance/test_docs_page_conformance.py` (rows, page data, then bytes; -the Python builders derive the schema rows from the model with the port's own naming helpers). -The C#, Java (Kotlin through Java) and Rust page generators are planned. +yields (`requirements.toon`, `agent/requirements.md`, the model-only `agent/schema.md`) plus the +data each page's shared template is fed and, under `rows/`, the ledger and model-only schema +rows that data is built from (the shapes the docs site reuses). Every builder reads the docs view +alone, its `storage` section included, so no port walks the model for a page. The TypeScript +builders are the source of the expected bytes. The human `requirements.md` page is retired: the +explorer shows the ledger. The corpus README writes down what a model-only schema page contains +and what it leaves out. + +**Held to it, in every port** (rows, page data, then bytes, and the set of files written): +`server/typescript/packages/cli/test/docs-page-conformance.test.ts`, +`server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs`, +`server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java` +(Kotlin's generators call the same JVM page builder), +`server/python/tests/conformance/test_docs_page_conformance.py` and +`server/rust/metaobjects-codegen/tests/docs_page_conformance.rs`. Rust has no requirement ledger +of its own (RS-V2), so its pages list every requirement the view carries. + +### `fixtures/agent-pages-pointer/` (3 cases) + +All 3 cases → [features/cli.md](features/cli.md#agent-context-scaffold). Each case is a project +root and the section the always-on `.metaobjects/AGENTS.md` gains above `## Rules`: the agent +pages the committed `.metaobjects/.gen-state/.hashes/` record, in a fixed order, and nothing at +all when none is recorded. **Held to it:** +`server/typescript/packages/sdk/test/agent-context/agent-pages.test.ts` and +`server/python/tests/unit/test_agent_docs.py`, the two ports that write the always-on file. C# +and Java hand `agent-docs` to the Node CLI, and Rust scaffolds no agent context. ### `fixtures/requirement-test-identity-conformance/` (27 cases) diff --git a/docs/features/cli.md b/docs/features/cli.md index b41e41c39a..505d5487e5 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -943,6 +943,14 @@ file gets the fresh text beside it as `.new`, and the `.metaobjects/.agent manifest is rewritten only when its text changed. `--skills-dir` and `--no-skills` stay with the Node CLI. Until the other ports' commands land, their stubs below still redirect. +**The always-on file points at the agent pages only when they are wired.** When the project's +committed `.metaobjects/.gen-state/.hashes/` record an agent page the last `gen` wrote +(`agent/schema.md`, `agent/ui.md`, `agent/requirements.md`, `AGENT-API.md`, `requirements.toon`), +both `meta agent-docs` and Python's `metaobjects agent-docs` add a section above `## Rules` in +`.metaobjects/AGENTS.md` that names each one by its path. With none recorded the file is exactly +as shipped, so it never sends an agent to a page that does not exist. The section's template +is the shipped manifest's `agentPagesTemplate`, and `fixtures/agent-pages-pointer/` gates it. + The C# and Java/Kotlin CLIs keep a **non-executing `agent-docs` pointer stub** that prints `agent-context scaffolding moved to the meta CLI — run: npx meta agent-docs --server ` to stderr and exits non-zero. The **live staleness check** diff --git a/fixtures/docs-page-conformance/README.md b/fixtures/docs-page-conformance/README.md index 894f1d8dd9..7ff6d2c247 100644 --- a/fixtures/docs-page-conformance/README.md +++ b/fixtures/docs-page-conformance/README.md @@ -109,7 +109,7 @@ the project's own migration tool, from the schema `meta schema` prints. A case s from that package, and review the diff: it is the cross-port contract. - Python: `server/python/tests/conformance/test_docs_page_conformance.py`. - C#: `server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs`. -- Java and Kotlin: `server/java/codegen-base/src/test/java/com/metaobjects/generator/docs/DocsPageConformanceTest.java`. +- Java and Kotlin: `server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java` (the Kotlin generators call the same JVM page builder). - Rust: `server/rust/metaobjects-codegen/tests/docs_page_conformance.rs`. Each checks rows, page data, then the bytes its `requirements` and `agent-docs` generators write. diff --git a/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs b/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs index fa63fb7a8e..5ec3753546 100644 --- a/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs +++ b/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs @@ -405,13 +405,11 @@ private static string JsText(JsonNode? n) => /// view alone. : the project chose a meta migrate dialect /// (migrate.dialect in .metaobjects/config.json). Null when the model declares no table /// and no view: no page. - public static Dictionary? AgentSchemaData(JsonObject view, bool hasMigrate, Func? inScope = null) + public static Dictionary? AgentSchemaData(JsonObject view, bool hasMigrate) { var storage = Obj(view["storage"]); - // A dependency's node the project did not take into scope is not the project's schema. - bool Scoped(string id) => inScope is null || inScope(id); - var tables = Objs(storage["tables"]).Where(t => Scoped(Str(Obj(t["declaredBy"])["id"]))).ToList(); - var views = Objs(storage["views"]).Where(v => Scoped(Str(Obj(v["declaredBy"])["id"]))).ToList(); + var tables = Objs(storage["tables"]).ToList(); + var views = Objs(storage["views"]).ToList(); if (tables.Count == 0 && views.Count == 0) return null; var members = MembersById(view); string FieldName(string id) => members.TryGetValue(id, out var m) ? Str(m["name"]) : ""; @@ -475,7 +473,7 @@ private static string JsText(JsonNode? n) => var relationships = new List(); foreach (var n in byOrder) { - if (Str(n["type"]) != "object" || !Scoped(Str(n["id"]))) continue; + if (Str(n["type"]) != "object") continue; foreach (var rel in DirectMembers(n, "relationship")) { string? through = AttrText(rel, "through"); @@ -567,7 +565,7 @@ private static string RenderTemplate(string text, object data) => /// requirements and the agent-docs generator's pages. public static IEnumerable<(string Path, string Content)> Render( JsonObject view, bool hasMigrate, string? templateRoot, Func? inLedger, - bool includeRequirements, bool includeAgent, Func? inScope = null) + bool includeRequirements, bool includeAgent) { var rows = RequirementRows(view, inLedger); if (includeRequirements && rows.Count > 0) @@ -577,7 +575,7 @@ private static string RenderTemplate(string text, object data) => view, RenderTemplate(Template("requirements", LedgerTemplate, templateRoot), LedgerData(rows, embedded: true)), inLedger); if (data is not null) yield return (AgentRequirementsPath, RenderTemplate(Template("agent", AgentRequirementsTemplate, templateRoot), data)); - if (AgentSchemaData(view, hasMigrate, inScope) is { } schema) + if (AgentSchemaData(view, hasMigrate) is { } schema) yield return (AgentSchemaPath, RenderTemplate(Template("agent", AgentSchemaTemplate, templateRoot), schema).TrimEnd('\n') + "\n"); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs index 524bf6612a..1052c46711 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs @@ -37,12 +37,10 @@ public IEnumerable Generate(GenContext ctx) var view = DocsView.Build(ctx.Root); // The project chose `meta migrate` (migrate.dialect in .metaobjects/config.json). bool hasMigrate = !string.IsNullOrEmpty(ctx.Config.Dialect); - // An object a dependency brought and the project did not take into scope is left out of the schema. - var inScope = ctx.Root.Objects().Where(ctx.Root.InScope).Select(o => o.ResolutionKey()).ToHashSet(StringComparer.Ordinal); string prefix = SubDir.TrimEnd('/') is { Length: > 0 } sub ? sub + "/" : ""; foreach (var (path, content) in DocsViewPages.Render( view, hasMigrate, TemplateRoot, fqn => imports?.InLedger(fqn) ?? true, - includeRequirements: false, includeAgent: true, inScope.Contains)) + includeRequirements: false, includeAgent: true)) yield return new EmittedFile(prefix + path, content) { WholeModel = true }; } } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java index 6089ece396..fb53ee9521 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java @@ -46,7 +46,7 @@ protected List generate(MetaDataLoader loader) { Path templateDir = hasArg(ARG_TEMPLATE_DIR) ? Path.of(getArg(ARG_TEMPLATE_DIR)) : null; JsonObject view = DocsView.build(loader.getRoot()); List files = new ArrayList<>(); - for (Map.Entry page : DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, null).entrySet()) { + for (Map.Entry page : DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, RequirementsGenerator.inLedger(loader)).entrySet()) { files.add(new EmittedFile(page.getKey(), page.getValue())); } return files; diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java index 65f3bf30ab..76dedbd522 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java @@ -39,9 +39,18 @@ protected List generate(MetaDataLoader loader) { Path templateDir = hasArg(ARG_TEMPLATE_DIR) ? Path.of(getArg(ARG_TEMPLATE_DIR)) : null; JsonObject view = DocsView.build(loader.getRoot()); List files = new ArrayList<>(); - for (Map.Entry page : DocsPagesEmitter.requirementsPages(view, subDir, templateDir, null).entrySet()) { + for (Map.Entry page : DocsPagesEmitter.requirementsPages(view, subDir, templateDir, inLedger(loader)).entrySet()) { files.add(new EmittedFile(page.getKey(), page.getValue())); } return files; } + + /** + * The requirements this project's ledger counts: its own, and a dependency's only when + * {@code requirements.inherit} names that dependency's package ({@code DependencySet#inLedger}). + */ + static java.util.function.Predicate inLedger(MetaDataLoader loader) { + com.metaobjects.config.DependencySet deps = loader.getRoot().getDependencySet(); + return deps.isEmpty() ? null : deps::inLedger; + } } From d50c9537f215a16197ed226bafa579a61adccc87 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 07:50:07 -0500 Subject: [PATCH 12/21] fix(codegen-ts): schema page keeps its own trailing break (layout ratchet) --- .../packages/codegen-ts/src/generators/docs-view-pages.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts b/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts index 85b97dd8cf..4d8d7c1670 100644 --- a/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts +++ b/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts @@ -346,7 +346,8 @@ export function renderAgentSchemaPageFromView(view: DocsView, hasMigrate: boolea const data = agentSchemaPageDataFromView(view, hasMigrate); if (data === undefined) return ""; const page = renderDocPage("agent/schema.md", data, provider ?? frameworkTemplatesProvider, "agent/schema.md"); - return `${page.replace(/\n+$/, "")}\n`; + // Keep one of the page's own trailing breaks (the template ends with one). + return page.replace(/(\n)\n+$/, "$1"); } /** From 30ef3e190e7d3d99e99d18bea256e6b0f82ca203 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 07:51:21 -0500 Subject: [PATCH 13/21] chore(site): payload counts 49 corpora --- examples/showcase/site-payload.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 84198022c1..2f6dbbbdb6 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -8,7 +8,7 @@ }, "counts": { "fixtures": 584, - "corpora": 48, + "corpora": 49, "baseTypes": 21 }, "snippets": { From f3fc59d0eb4707865c4a2635092332bd12ca88cf Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 08:04:58 -0500 Subject: [PATCH 14/21] no-mistakes(review): apply reviewer inline fixes --- docs/ports/kotlin.md | 4 ++-- docs/ports/rust.md | 2 +- .../typescript/packages/sdk/src/agent-context/assemble.ts | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index daa80c3a9b..a920fd572d 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -164,7 +164,7 @@ Every generator lays its output out with `KotlinWriter` The layout ratchet (`KotlinLayoutRatchetTest`) fails a generator that types its own line breaks or indentation, or imports KotlinPoet; its shrink-only allowlist of unconverted emitters is empty. -The 20 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): +The 22 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): | Generator | Output | Per | |---|---|---| @@ -321,7 +321,7 @@ copies `KotlinSharedModelGenerator.kt` into a `codegen/` module under your packa ### Declarative template-codegen (`TemplateScopeGenerator`) -The 20 generators above are not the ceiling. When you need a shape +The 22 generators above are not the ceiling. When you need a shape none of them emits, Kotlin has **both** authoring paths — and which to reach for is a real decision (tradeoff table: [`codegen-concepts.md` §3](../features/codegen-concepts.md)). diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 9fc7033340..4157deb91b 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -82,7 +82,7 @@ The file takes that one key: a layer is only a generator, so there are no layer name, or `{"name": "", "options": {...}}` for a generator that takes options; the generator's `configure` reads them and refuses a key it does not know (`ERR_UNKNOWN_GENERATOR_OPTION`, naming the options it takes). Of the shipped generators only the docs generators take options -(`metamodel-docs`, `requirements` and `agent-docs` take `subDir`; `docs-site` takes the six in [its section](#docs-site-the-model-explorer)), so +(`metamodel-docs` and `agent-docs` take `subDir`; `docs-site` takes the six in [its section](#docs-site-the-model-explorer)), so any other option fails the run, also a run `--generators` narrows to other generators. A project with no such file runs every generator but `service-routes` and the four docs generators, which run only when they are listed: an HTTP server is a choice the project makes, not a default, and so are diff --git a/server/typescript/packages/sdk/src/agent-context/assemble.ts b/server/typescript/packages/sdk/src/agent-context/assemble.ts index b72af6a324..f6af4bee39 100644 --- a/server/typescript/packages/sdk/src/agent-context/assemble.ts +++ b/server/typescript/packages/sdk/src/agent-context/assemble.ts @@ -128,6 +128,9 @@ function applyTemplate( }); } +/** Where the always-on file goes, relative to the project root. */ +export const ALWAYS_ON_PATH = ".metaobjects/AGENTS.md"; + /** * Assemble the consumer files for a resolved stack. Pure given the content tree. * @@ -139,9 +142,6 @@ function applyTemplate( * `skillsDir` is where the skills install (default {@link DEFAULT_SKILLS_DIR}); the always-on * text names it, so an assistant that does not load skills can open them by path. */ -/** Where the always-on file goes, relative to the project root. */ -export const ALWAYS_ON_PATH = ".metaobjects/AGENTS.md"; - export function assemble(opts: { contentRoot: string; stack: Stack; docsRef?: string; skillsDir?: string }): AssembledFile[] { const { contentRoot, stack } = opts; const docsRef = opts.docsRef ?? "main"; From dbea06ce8257ac4fa83a773da842321ca21aa409 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 08:10:37 -0500 Subject: [PATCH 15/21] no-mistakes(review): Share requirement-ledger filter; Kotlin pages honour it --- .../docs/pages/DocsPagesEmitter.java | 12 ++ .../generator/AgentDocsGenerator.java | 2 +- .../generator/RequirementsGenerator.java | 11 +- .../kotlin/KotlinAgentDocsGenerator.kt | 2 +- .../kotlin/KotlinRequirementsGenerator.kt | 2 +- .../KotlinRequirementPagesLedgerTest.kt | 148 ++++++++++++++++++ .../packages/codegen-ts/src/docs-run.ts | 5 +- .../packages/codegen-ts/src/runner.ts | 3 +- 8 files changed, 169 insertions(+), 16 deletions(-) create mode 100644 server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementPagesLedgerTest.kt diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java b/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java index 269221f6d4..52eeb71ee8 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java @@ -1,7 +1,9 @@ package com.metaobjects.docs.pages; import com.google.gson.JsonObject; +import com.metaobjects.config.DependencySet; import com.metaobjects.docs.metamodel.MetamodelDocsEmitter; +import com.metaobjects.loader.MetaDataLoader; import com.metaobjects.render.Escapers; import com.metaobjects.render.Provider; import com.metaobjects.render.RenderRequest; @@ -78,6 +80,16 @@ private static String render(String ref, Map data, Provider prov return new Renderer().render(new RenderRequest(null, ref, data, provider, Escapers.FORMAT_MARKDOWN, null, null)); } + /** + * The requirements this project's ledger counts: its own, and a dependency's only when + * {@code requirements.inherit} names that dependency's package ({@link DependencySet#inLedger}). + * Null for a project with no dependency: every requirement in the view is its own. + */ + public static Predicate inLedger(MetaDataLoader loader) { + DependencySet deps = loader.getRoot().getDependencySet(); + return deps.isEmpty() ? null : deps::inLedger; + } + /** {@code requirements.toon}, or nothing for an empty ledger. Keyed by path relative to {@code subDir}. */ public static Map requirementsPages(JsonObject view, String subDir, Path templateDir, Predicate inLedger) { diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java index fb53ee9521..cffdbb1959 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java @@ -46,7 +46,7 @@ protected List generate(MetaDataLoader loader) { Path templateDir = hasArg(ARG_TEMPLATE_DIR) ? Path.of(getArg(ARG_TEMPLATE_DIR)) : null; JsonObject view = DocsView.build(loader.getRoot()); List files = new ArrayList<>(); - for (Map.Entry page : DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, RequirementsGenerator.inLedger(loader)).entrySet()) { + for (Map.Entry page : DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, DocsPagesEmitter.inLedger(loader)).entrySet()) { files.add(new EmittedFile(page.getKey(), page.getValue())); } return files; diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java index 76dedbd522..5aa79ee1ed 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/RequirementsGenerator.java @@ -39,18 +39,9 @@ protected List generate(MetaDataLoader loader) { Path templateDir = hasArg(ARG_TEMPLATE_DIR) ? Path.of(getArg(ARG_TEMPLATE_DIR)) : null; JsonObject view = DocsView.build(loader.getRoot()); List files = new ArrayList<>(); - for (Map.Entry page : DocsPagesEmitter.requirementsPages(view, subDir, templateDir, inLedger(loader)).entrySet()) { + for (Map.Entry page : DocsPagesEmitter.requirementsPages(view, subDir, templateDir, DocsPagesEmitter.inLedger(loader)).entrySet()) { files.add(new EmittedFile(page.getKey(), page.getValue())); } return files; } - - /** - * The requirements this project's ledger counts: its own, and a dependency's only when - * {@code requirements.inherit} names that dependency's package ({@code DependencySet#inLedger}). - */ - static java.util.function.Predicate inLedger(MetaDataLoader loader) { - com.metaobjects.config.DependencySet deps = loader.getRoot().getDependencySet(); - return deps.isEmpty() ? null : deps::inLedger; - } } diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt index 3a80e3b522..d6bde43274 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt @@ -31,7 +31,7 @@ open class KotlinAgentDocsGenerator : FileEmittingGenerator() { val subDir = getArg(ARG_SUB_DIR, "") val templateDir: Path? = if (hasArg(ARG_TEMPLATE_DIR)) Path.of(getArg(ARG_TEMPLATE_DIR)) else null val view = DocsView.build(loader.root) - return DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, null) + return DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, DocsPagesEmitter.inLedger(loader)) .map { (path, content) -> EmittedFile(path, content) } } diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementsGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementsGenerator.kt index 492902ebec..30a8996dd7 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementsGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementsGenerator.kt @@ -26,7 +26,7 @@ open class KotlinRequirementsGenerator : FileEmittingGenerator() { val subDir = getArg(ARG_SUB_DIR, "") val templateDir: Path? = if (hasArg(ARG_TEMPLATE_DIR)) Path.of(getArg(ARG_TEMPLATE_DIR)) else null val view = DocsView.build(loader.root) - return DocsPagesEmitter.requirementsPages(view, subDir, templateDir, null).map { (path, content) -> EmittedFile(path, content) } + return DocsPagesEmitter.requirementsPages(view, subDir, templateDir, DocsPagesEmitter.inLedger(loader)).map { (path, content) -> EmittedFile(path, content) } } companion object { diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementPagesLedgerTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementPagesLedgerTest.kt new file mode 100644 index 0000000000..32dcdd3c37 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementPagesLedgerTest.kt @@ -0,0 +1,148 @@ +package com.metaobjects.generator.kotlin + +import com.google.gson.JsonElement +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import com.metaobjects.config.SourceResolver +import com.metaobjects.generator.util.GeneratedFileWriter +import com.metaobjects.loader.FileSource +import com.metaobjects.loader.LoaderOptions +import com.metaobjects.loader.MetaDataLoader +import com.metaobjects.loader.MetaDataSource +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.Paths +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The Kotlin `requirements` and `agent-docs` generators list the project's own ledger: its own + * requirements, and a dependency's only when `requirements.inherit` names that dependency's package. + * The projects and the ledger each must list (`expectLedger`) are the shared + * `fixtures/dependency-conformance` cases every port's loader is held to. A requirement in the + * dependency's artifact that the case's ledger does not hold must appear on neither page. + */ +class KotlinRequirementPagesLedgerTest { + + private val scratch = mutableListOf() + + @AfterTest + fun cleanUp() { + scratch.forEach { it.toFile().deleteRecursively() } + scratch.clear() + } + + private fun tempDir(prefix: String): Path = Files.createTempDirectory(prefix).also { scratch.add(it) } + + private fun corpus(): Path { + var dir: Path? = Paths.get("").toAbsolutePath() + while (dir != null && !Files.isDirectory(dir.resolve("fixtures"))) dir = dir.parent + return dir!!.resolve("fixtures/dependency-conformance") + } + + private fun case(name: String): JsonObject = + JsonParser.parseString(Files.readString(corpus().resolve("cases.json"))) + .asJsonObject.getAsJsonArray("cases") + .map { it.asJsonObject }.first { it["name"].asString == name } + + private fun write(p: Path, bytes: ByteArray) { + Files.createDirectories(p.parent) + Files.write(p, bytes) + } + + /** Every requirement a case's metadata declares, keyed `::`, with its statement. */ + private fun declaredStatements(case: JsonObject): Map { + val docs = case.getAsJsonObject("tree").entrySet().map { JsonParser.parseString(it.value.asString) } + + case.getAsJsonObject("treeFiles").entrySet().map { + JsonParser.parseString(Files.readString(corpus().resolve(it.value.asString))) + } + val out = mutableMapOf() + fun walk(node: JsonElement, pkg: String?, path: String?) { + if (!node.isJsonObject) return + for ((key, value) in node.asJsonObject.entrySet()) { + if (!value.isJsonObject) continue + val body = value.asJsonObject + val ownPkg = body["package"]?.asString ?: pkg + var childPath = path + if (key.startsWith("requirement.")) { + childPath = if (path == null) body["name"].asString else "$path.${body["name"].asString}" + out["$ownPkg::$childPath"] = body["@statement"].asString + } + body.getAsJsonArray("children")?.forEach { walk(it, ownPkg, childPath) } + } + } + docs.forEach { walk(it, null, null) } + return out + } + + private fun load(case: JsonObject): MetaDataLoader { + val project = tempDir("kreq-ledger-project-") + for ((k, v) in case.getAsJsonObject("tree").entrySet()) write(project.resolve(k), v.asString.toByteArray()) + for ((k, v) in case.getAsJsonObject("treeFiles").entrySet()) { + write(project.resolve(k), Files.readAllBytes(corpus().resolve(v.asString))) + } + write(project.resolve(".metaobjects/config.json"), case.getAsJsonObject("config").toString().toByteArray()) + write(project.resolve(".metaobjects/deps.lock.json"), case.getAsJsonObject("lock").toString().toByteArray()) + + val collection = SourceResolver.resolveCollectionWithDependencies(project) + val deps = collection.dependencies() + val sources = ArrayList(deps.sources()) + collection.ownFiles().forEach { sources.add(FileSource(it)) } + val loader = MetaDataLoader(LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "kreq-ledger") + loader.init() + loader.setDependencies(deps) + loader.load(sources) + return loader + } + + /** The two pages that list requirements, by path; a page the run did not write is absent. */ + private fun pages(loader: MetaDataLoader): Map { + val out = tempDir("kreq-ledger-out-") + GeneratedFileWriter.beginRun().use { run -> + for (gen in listOf(KotlinRequirementsGenerator(), KotlinAgentDocsGenerator())) { + run.attributeTo(gen.javaClass.simpleName) + gen.setArgs(mapOf("outputDir" to out.toString())).execute(loader) + } + } + return listOf("requirements.toon", "agent/requirements.md") + .filter { Files.isRegularFile(out.resolve(it)) } + .associateWith { Files.readString(out.resolve(it)) } + } + + private fun assertPagesListTheLedger(caseName: String) { + val case = case(caseName) + val ledger = case.getAsJsonObject("expectLedger").keySet() + val declared = declaredStatements(case) + assertTrue(declared.keys.containsAll(ledger), "$caseName: the corpus ledger names an undeclared requirement") + val pages = pages(load(case)) + + if (ledger.isEmpty()) { + assertTrue(pages.isEmpty(), "$caseName: an empty ledger writes no requirement page, got ${pages.keys}") + return + } + assertTrue(pages.keys == setOf("requirements.toon", "agent/requirements.md"), "$caseName: ${pages.keys}") + for ((page, text) in pages) { + for ((fqn, statement) in declared) { + if (fqn in ledger) { + assertTrue(statement in text, "$caseName: $page omits the ledger's $fqn") + } else { + assertFalse(statement in text, "$caseName: $page lists $fqn, which the ledger does not hold") + } + } + } + } + + @Test fun `an uninherited dependency's requirements stay off the pages beside the project's own`() = + assertPagesListTheLedger("an-own-requirement-beside-an-uninherited-dependency-ledger-is-the-whole-ledger") + + @Test fun `requirements inherit naming the dependency's package brings its requirements onto the pages`() = + assertPagesListTheLedger("requirements-inherit-naming-the-package-takes-on-its-ledger") + + @Test fun `a wildcard inherit lists no dependency requirement`() = + assertPagesListTheLedger("a-wildcard-inherit-does-not-name-a-package") + + @Test fun `a scope include naming the dependency lists none of its requirements`() = + assertPagesListTheLedger("a-scope-include-naming-the-package-does-not-inherit-its-requirements") +} diff --git a/server/typescript/packages/codegen-ts/src/docs-run.ts b/server/typescript/packages/codegen-ts/src/docs-run.ts index a26558191f..00d5f536c7 100644 --- a/server/typescript/packages/codegen-ts/src/docs-run.ts +++ b/server/typescript/packages/codegen-ts/src/docs-run.ts @@ -65,8 +65,9 @@ export function docsRunFacts( /** * Memoize a schema builder so it runs at most once per run, and only when a generator asks: - * a run that lists no `agentDocsFile()` never builds a schema, and never prints the reasons - * one could not be built. + * `agentDocsFile()` and every generator that builds the docs view (`docsSiteFile()`, a + * view-scoped template) ask. A run that lists none of them never builds a schema, and never + * prints the reasons one could not be built. */ export function onceAgentSchema( build: () => AgentSchemaInput | undefined, diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index 1b1f3a27d3..50538b571c 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -162,7 +162,8 @@ export interface RunGenOpts { * Builds the physical schema `agent/schema.md` describes, with the project's dialect and * column naming. codegen-ts cannot build it (the schema builder is `migrate-ts`'s), so the * caller that can supplies it; the runner calls it at most once, and only when a generator - * asks (`ctx.docs.agentSchema`). Absent: `agentDocsFile()` writes no schema page. + * asks (`ctx.docs.agentSchema`). Absent: `agentDocsFile()` writes the model-only schema page, + * and the docs view's physical storage facts stay null. */ agentSchema?: () => AgentSchemaInput | undefined; /** Threaded onto `GenContext.schemaSettings`; see there. */ From 8c967b8871f2202dc03e423ebbbb8cb1a2ce39a1 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 08:12:16 -0500 Subject: [PATCH 16/21] no-mistakes(review): Align agent-schema contract comments with behavior --- server/typescript/packages/codegen-ts/src/docs-run.ts | 8 ++++---- server/typescript/packages/codegen-ts/src/runner.ts | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/server/typescript/packages/codegen-ts/src/docs-run.ts b/server/typescript/packages/codegen-ts/src/docs-run.ts index 00d5f536c7..36ba82fbf6 100644 --- a/server/typescript/packages/codegen-ts/src/docs-run.ts +++ b/server/typescript/packages/codegen-ts/src/docs-run.ts @@ -64,10 +64,10 @@ export function docsRunFacts( } /** - * Memoize a schema builder so it runs at most once per run, and only when a generator asks: - * `agentDocsFile()` and every generator that builds the docs view (`docsSiteFile()`, a - * view-scoped template) ask. A run that lists none of them never builds a schema, and never - * prints the reasons one could not be built. + * Memoize a schema builder so it runs at most once per run, on first demand. `agentDocsFile()` + * and every generator that builds the docs view (`docsSiteFile()`, a view-scoped template) ask, + * so a run with a dialect and any one of them may build the schema and print the reasons one + * could not be built. A run that lists none of them never builds it. */ export function onceAgentSchema( build: () => AgentSchemaInput | undefined, diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index 50538b571c..0caa37f097 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -162,8 +162,8 @@ export interface RunGenOpts { * Builds the physical schema `agent/schema.md` describes, with the project's dialect and * column naming. codegen-ts cannot build it (the schema builder is `migrate-ts`'s), so the * caller that can supplies it; the runner calls it at most once, and only when a generator - * asks (`ctx.docs.agentSchema`). Absent: `agentDocsFile()` writes the model-only schema page, - * and the docs view's physical storage facts stay null. + * asks (`ctx.docs.agentSchema`). Absent: `agentDocsFile()` writes the model-only + * `agent/schema.md` built from the docs view, and the view's physical storage facts stay null. */ agentSchema?: () => AgentSchemaInput | undefined; /** Threaded onto `GenContext.schemaSettings`; see there. */ From b699803638a8bf3ab11fc647270f5027f820b294 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 08:14:31 -0500 Subject: [PATCH 17/21] no-mistakes(review): apply reviewer inline fixes --- .../codegen-ts/src/generators/agent-docs-file.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts b/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts index 2e2a75e8f9..db9c606d45 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts @@ -17,11 +17,12 @@ // schema ← the expected-schema snapshot `meta migrate` diffs and emits from // (injected; see agent-schema-input.ts for why codegen-ts refuses to // compute it) + `resolveObjectNames`, the field→column resolver the -// names artifact and the DDL already share +// names artifact and the DDL already share; with no dialect, the +// model-only page every port writes, read off the docs view // ui ← `buildEntityUiDescriptor`, the same derivation emitted as the // `` const that `useEntityForm` reads at runtime -// requirements ← `walkRequirements` + `requirementRows`, the same walk the ledger -// surface and the generated test stubs are built on +// requirements ← the docs view's requirement rows and resolved `implementedBy`, the +// same view every port's page builders read // // RUN-DEPENDENT, like the api reference. Physical names, the dialect and view dispatch all // depend on the gen config, which `meta gen` reads before it builds the schema. @@ -29,7 +30,7 @@ // different contract, not a relaxation of that one. // // AN EMPTY PAGE IS NO FILE. Each renderer returns "" when its tier has nothing to -// describe — no physical schema, no UI, no ledger — and an empty render emits nothing. +// describe — no table and no view, no UI, no ledger — and an empty render emits nothing. // That is what makes the surface safe to leave on: a headless project with no ledger sees // no `agent/` directory rather than three pages of headings. // From 3bc6e171ecbd0079466ac3446cb8fe47e9387bda Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 08:21:54 -0500 Subject: [PATCH 18/21] no-mistakes(review): Agent-docs subDir replaces agent/; neutral pointer text --- .../files/527e422aeec9a36d.md | 7 ------- .../files/5497499d5dddc2cc.md | 7 +++++++ agent-context-shipped/manifest.json | 2 +- .../templates/agent-pages.md.mustache | 4 ++-- docs/features/cli.md | 7 +++++-- docs/ports/csharp.md | 4 +++- docs/ports/java.md | 2 +- docs/ports/kotlin.md | 2 +- fixtures/agent-pages-pointer/README.md | 11 +++++++--- .../cases/wired/expected-section.md | 4 ++-- .../DocsPageConformanceTests.cs | 21 +++++++++++++++++++ .../MetaObjects.Codegen/GeneratorRegistry.cs | 2 +- .../Generators/AgentDocsGenerator.cs | 11 ++++++---- .../docs/pages/DocsPagesEmitter.java | 19 ++++++++++------- .../generator/AgentDocsGenerator.java | 10 ++++----- .../docs/pages/DocsPageConformanceTest.java | 4 ++-- .../kotlin/KotlinAgentDocsGenerator.kt | 6 +++--- .../KotlinRequirementPagesLedgerTest.kt | 19 +++++++++++++++++ .../shipped/files/527e422aeec9a36d.md | 7 ------- .../shipped/files/5497499d5dddc2cc.md | 7 +++++++ .../agent_context/shipped/manifest.json | 2 +- 21 files changed, 108 insertions(+), 50 deletions(-) delete mode 100644 agent-context-shipped/files/527e422aeec9a36d.md create mode 100644 agent-context-shipped/files/5497499d5dddc2cc.md delete mode 100644 server/python/src/metaobjects/agent_context/shipped/files/527e422aeec9a36d.md create mode 100644 server/python/src/metaobjects/agent_context/shipped/files/5497499d5dddc2cc.md diff --git a/agent-context-shipped/files/527e422aeec9a36d.md b/agent-context-shipped/files/527e422aeec9a36d.md deleted file mode 100644 index 579a3509ae..0000000000 --- a/agent-context-shipped/files/527e422aeec9a36d.md +++ /dev/null @@ -1,7 +0,0 @@ -## Pages generated for this project - -`meta gen` writes these from the metadata (they are regenerated output, like the code). Read the -one for a tier before you change that tier: - -{{pageList}} - diff --git a/agent-context-shipped/files/5497499d5dddc2cc.md b/agent-context-shipped/files/5497499d5dddc2cc.md new file mode 100644 index 0000000000..bf233c2a66 --- /dev/null +++ b/agent-context-shipped/files/5497499d5dddc2cc.md @@ -0,0 +1,7 @@ +## Pages generated for this project + +The project's `gen` command writes these from the metadata (they are regenerated output, like the +code). Read the one for a tier before you change that tier: + +{{pageList}} + diff --git a/agent-context-shipped/manifest.json b/agent-context-shipped/manifest.json index bf05f04901..ca50485056 100644 --- a/agent-context-shipped/manifest.json +++ b/agent-context-shipped/manifest.json @@ -3,7 +3,7 @@ "docsRef": "main", "docsLinkPrefix": "https://github.com/metaobjectsdev/metaobjects/blob/", "skillsDir": ".claude/skills", - "agentPagesTemplate": "527e422aeec9a36d.md", + "agentPagesTemplate": "5497499d5dddc2cc.md", "stacks": [ { "id": "typescript", diff --git a/agent-context/templates/agent-pages.md.mustache b/agent-context/templates/agent-pages.md.mustache index 579a3509ae..bf233c2a66 100644 --- a/agent-context/templates/agent-pages.md.mustache +++ b/agent-context/templates/agent-pages.md.mustache @@ -1,7 +1,7 @@ ## Pages generated for this project -`meta gen` writes these from the metadata (they are regenerated output, like the code). Read the -one for a tier before you change that tier: +The project's `gen` command writes these from the metadata (they are regenerated output, like the +code). Read the one for a tier before you change that tier: {{pageList}} diff --git a/docs/features/cli.md b/docs/features/cli.md index 505d5487e5..e70dcb5e27 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -948,8 +948,11 @@ committed `.metaobjects/.gen-state/.hashes/` record an agent page the last `gen` (`agent/schema.md`, `agent/ui.md`, `agent/requirements.md`, `AGENT-API.md`, `requirements.toon`), both `meta agent-docs` and Python's `metaobjects agent-docs` add a section above `## Rules` in `.metaobjects/AGENTS.md` that names each one by its path. With none recorded the file is exactly -as shipped, so it never sends an agent to a page that does not exist. The section's template -is the shipped manifest's `agentPagesTemplate`, and `fixtures/agent-pages-pointer/` gates it. +as shipped, so it never sends an agent to a page that does not exist. It recognises the pages +by those default paths only: an `agent-docs` run with a custom `subDir` (`llm/schema.md`) writes +pages the section does not name, so they get no line rather than a wrong one, and a project whose +only agent pages are such gets no section. The section's template is the shipped manifest's +`agentPagesTemplate`, and `fixtures/agent-pages-pointer/` gates it. The C# and Java/Kotlin CLIs keep a **non-executing `agent-docs` pointer stub** that prints `agent-context scaffolding moved to the meta CLI — run: npx meta diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index f2ae74b7ae..e7c92876ad 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -371,7 +371,9 @@ views, relationships and enums, named by this port's naming helpers). Both build the docs view (`MetaObjects.DocsView`, its `storage` section for the schema) and render the shared `templates/requirements/` and `templates/agent/` Mustache pages, byte for byte what `fixtures/docs-page-conformance/` pins (`DocsPageConformanceTests`). A `/.mustache` -under `TemplateRoot` overrides a shipped page. `agent/ui.md` and the physical schema (SQL types, +under `TemplateRoot` overrides a shipped page. `agent-docs`'s `SubDir` is the directory the pages +land in, `agent` by default (`"llm"` writes `llm/schema.md`; `""` writes at the root), as in every +port. `agent/ui.md` and the physical schema (SQL types, defaults, indexes) stay TypeScript's. The always-on agent file comes from the Node CLI (`npx meta agent-docs`), which names these pages once a `gen` has written them. diff --git a/docs/ports/java.md b/docs/ports/java.md index 16a5ae60e0..9c610ad074 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -470,7 +470,7 @@ name in every port. | `plantuml` | `PlantUMLGenerator` | `metaobjects-codegen-plantuml` | One PlantUML class diagram of the object model (`outputDir`, `outputFilename`; `showAttrs`, `showFields`, `showAbstracts`, `drawKeys`, `drawRefs` choose what is drawn). Ejectable: the copy takes `PlantUMLWriter` with it. | | `metamodel-docs` | `MetamodelDocsGenerator` | `metaobjects-codegen-base` | The reference of the built-in metamodel as Markdown: `INDEX.md`, `providers.md` and one `types/.md` per type family, rendered from the shared `templates/metamodel/` Mustache set over the build's own registry, so every port writes the same pages. Args: `outputDir` (required, generated files only), `subDir` (default `metamodel`; empty writes at the root) and `metamodelTemplateDir` (a directory holding `metamodel/.mustache` that win over the packaged ones; a same-path resource earlier on the classpath does too). Reads no model objects. Ejectable: the page data and templates stay in the package. | | `requirements` | `RequirementsGenerator` | `metaobjects-codegen-base` | The requirement ledger as `requirements.toon`, for tools, rendered from the shared `templates/requirements/` Mustache page over the model's docs view, so every port writes the same bytes (`fixtures/docs-page-conformance/`). People read the ledger in the explorer (`docs-site`); no port writes a human `requirements.md`. Args: `outputDir` (required, generated files only), `subDir` (default empty: the root) and `templateDir` (a directory holding `requirements/.mustache` that win over the packaged ones). No `requirement.*` node, no file. Ejectable: the page data and templates stay in the package. | -| `agent-docs` | `AgentDocsGenerator` | `metaobjects-codegen-base` | Pages written for a coding agent, from the shared `templates/agent/` Mustache pages over the docs view: `agent/requirements.md` (the node index and the ledger) and the model-only `agent/schema.md` (tables, views, relationships and enums, without the SQL types, defaults, indexes and checks only the TypeScript migration engine knows). `agent/ui.md` stays a TypeScript page. Byte-identical to the TypeScript pages (`fixtures/docs-page-conformance/`). Args: `outputDir` (required, generated files only), `subDir` (default empty) and `templateDir` (`agent/.mustache` and `requirements/.mustache` overrides). The schema page says to change the schema with `meta migrate` when `.metaobjects/config.json` sets `migrate.dialect`. No requirement, no requirement page; no table and no view, no schema page. Ejectable. | +| `agent-docs` | `AgentDocsGenerator` | `metaobjects-codegen-base` | Pages written for a coding agent, from the shared `templates/agent/` Mustache pages over the docs view: `agent/requirements.md` (the node index and the ledger) and the model-only `agent/schema.md` (tables, views, relationships and enums, without the SQL types, defaults, indexes and checks only the TypeScript migration engine knows). `agent/ui.md` stays a TypeScript page. Byte-identical to the TypeScript pages (`fixtures/docs-page-conformance/`). Args: `outputDir` (required, generated files only), `subDir` (the directory the pages land in, default `agent`; `llm` writes `llm/schema.md`, empty writes at the root, as in every port) and `templateDir` (`agent/.mustache` and `requirements/.mustache` overrides). The schema page says to change the schema with `meta migrate` when `.metaobjects/config.json` sets `migrate.dialect`. No requirement, no requirement page; no table and no view, no schema page. Ejectable. | | `docs-site` | `DocsSiteGenerator` | `metaobjects-codegen-base` | The model explorer, with no Node: under `/` (default `site`) it writes the explorer app (`index.html` and `assets/`, the same bytes in every port), `explorer.json` (the docs view, built from the model this run loaded; byte-identical to TypeScript's for the same inputs, gated by `fixtures/explorer-conformance/`), `explorer-model.js` and `explorer-stamp.js`. Each object lists the files generated for it (`generatedBy`, `sourceNode`): this execution's, and what the committed hash manifest records for the module's other ``s. The execution builds the site after every other generator it runs, so `metaobjects:verify` renders the lists the write run wrote. Args: `outputDir` (required), `subDir`, `title` (default: the module directory's name), `stamp` (footer text, default none), `prompts` (a directory of prompt `.mustache` sources beside the metadata and `templates/`), `verifyFile` (a `verify --format json` payload from the Node CLI, for the requirement verdicts; without it the requirement tree shows claims but no verdicts), `routesFile` (the routes the application mounts, `[{ node, method, path }]` with `node` a resolution key; without it no node lists routes) and `genStateDir` (default `.metaobjects/.gen-state`; read only when the generator runs outside `metaobjects:generate` and `metaobjects:verify`). An owned theme under `codegen/docs-site/` (`assets/explorer.css`, `assets/explorer.js`, `templates/explorer-*.mustache`) wins over the packaged one. Not ejectable: the builder is engine, the theme is what you own. The page-per-screen static export and the classic site stay TypeScript's. | | `html-docs` | `MetaDataHtmlDocumentationGenerator` | `metaobjects-codegen-base` | One HTML page describing the registered metamodel types (`outputDir`, `outputFilename`). It reads the type registry, not your model, so it documents the vocabulary your build loads, providers included. Ejectable: the copy takes `MetaDataHtmlDocumentationWriter` with it. | | `ai-docs` | `MetaDataAIDocumentationGenerator` | `metaobjects-codegen-base` | The same type reference as JSON, laid out for an AI reader (`outputDir`, `outputFilename`). Ejectable: the copy takes `MetaDataAIDocumentationWriter` with it. | diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index a920fd572d..7928a0d67c 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -188,7 +188,7 @@ The 22 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): | `KotlinApiDocsGenerator` | The Kotlin SDK api reference, under `/`: `.md` per entity, value object, projection, served report and template, a `README.md` index and `AGENT-API.md`. A `` entry like any other, run by `metaobjects:generate` and checked by `metaobjects:verify`. Args: `outputDir` (required, generated files only), `apiSubDir` (default `api/kotlin`), `layout` (`flat` or `package`), `projectName` and `modelBaseUrl`, as for the Java `api-docs` (with no `modelBaseUrl` the pages carry no `Model / metadata` link). The `metaobjects:docs` goal was removed in 8.1.0 ([migration](../features/migrations/docs-are-generators.md#java-and-kotlin)). Ejectable, with the page model, builder, renderer and path math | the whole model, once | | `KotlinMetamodelDocsGenerator` | The reference of the built-in metamodel, under `/`: `INDEX.md`, `providers.md` and one `types/.md` per type family, rendered from the shared `templates/metamodel/` Mustache set over the build's own registry, so every port writes the same pages. Args: `outputDir` (required, generated files only), `subDir` (default `metamodel`; empty writes at the root) and `metamodelTemplateDir` (a directory holding `metamodel/.mustache` that win over the packaged ones). Reads no model objects. Ejectable | once per project | | `KotlinRequirementsGenerator` | The requirement ledger as `requirements.toon` under `/`, rendered by the JVM page builder from the shared `templates/requirements/` page over the docs view, the same bytes as every port (`fixtures/docs-page-conformance/`). Args: `outputDir` (required), `subDir` (default empty) and `templateDir`. No `requirement.*` node, no file. Ejectable | once per project | -| `KotlinAgentDocsGenerator` | `agent/requirements.md` and the model-only `agent/schema.md` for a coding agent, from the shared `templates/agent/` pages over the docs view (the JVM page builder; `agent/ui.md` stays TypeScript). Args: `outputDir` (required), `subDir` (default empty) and `templateDir`. No requirement, no requirement page; no table and no view, no schema page. Ejectable | once per project | +| `KotlinAgentDocsGenerator` | `agent/requirements.md` and the model-only `agent/schema.md` for a coding agent, from the shared `templates/agent/` pages over the docs view (the JVM page builder; `agent/ui.md` stays TypeScript). Args: `outputDir` (required), `subDir` (the directory the pages land in, default `agent`; `llm` writes `llm/schema.md`, empty writes at the root) and `templateDir`. No requirement, no requirement page; no table and no view, no schema page. Ejectable | once per project | | `DocsSiteGenerator` (`docs-site`) | The model explorer, with no Node: the JVM `DocsSiteGenerator` itself, so Kotlin and Java write the same bytes. Under `/` (default `site`): the explorer app, `explorer.json` (the docs view of the loaded model, byte-identical to TypeScript's, gated by `fixtures/explorer-conformance/`), `explorer-model.js` and `explorer-stamp.js`, with each object's generated files from this execution (built after every other generator it runs) and from the committed hash manifest for the module's other executions. Args as in [the Java table](java.md#generators). Not ejectable: an owned theme under `codegen/docs-site/` wins over the packaged one | once per project | Maven wiring. The plugin bundles `metaobjects-codegen-kotlin`, so it is not a dependency of your diff --git a/fixtures/agent-pages-pointer/README.md b/fixtures/agent-pages-pointer/README.md index 77f9e43b4d..ef08545f2b 100644 --- a/fixtures/agent-pages-pointer/README.md +++ b/fixtures/agent-pages-pointer/README.md @@ -1,14 +1,19 @@ # agent-pages-pointer -The always-on agent file (`.metaobjects/AGENTS.md`) points at the pages `meta gen` writes for a -coding agent (`agent/schema.md`, `agent/ui.md`, `agent/requirements.md`, `AGENT-API.md`, -`requirements.toon`) only when the project's last `gen` wrote one. Every port that scaffolds the +The always-on agent file (`.metaobjects/AGENTS.md`) points at the pages the project's `gen` +writes for a coding agent (`agent/schema.md`, `agent/ui.md`, `agent/requirements.md`, +`AGENT-API.md`, `requirements.toon`) only when the project's last `gen` wrote one. Every port that scaffolds the always-on file reads what was written from the committed `.metaobjects/.gen-state/.hashes/` (one JSON file per package, keyed by project-relative path; a value is a hash or an object carrying one), renders the section from the template the shipped manifest names (`agentPagesTemplate`, from `agent-context/templates/agent-pages.md.mustache`), and inserts it above the file's `## Rules` heading. +The pages are recognised by those default paths only (a path that is one, or ends in `/` plus +one). An `agent-docs` run with a custom `subDir` writes `llm/schema.md`, which the section does not +name: it gets no line, never a wrong one, and with no other agent page there is no section. +Knowing which generator wrote a path would need the hashes to record it, which they do not. + Each case is a project root. `expected-section.md` is the rendered section: empty when no page is wired, which leaves the always-on file exactly as shipped. diff --git a/fixtures/agent-pages-pointer/cases/wired/expected-section.md b/fixtures/agent-pages-pointer/cases/wired/expected-section.md index 3926fbfc18..fe46f1c2b4 100644 --- a/fixtures/agent-pages-pointer/cases/wired/expected-section.md +++ b/fixtures/agent-pages-pointer/cases/wired/expected-section.md @@ -1,7 +1,7 @@ ## Pages generated for this project -`meta gen` writes these from the metadata (they are regenerated output, like the code). Read the -one for a tier before you change that tier: +The project's `gen` command writes these from the metadata (they are regenerated output, like the +code). Read the one for a tier before you change that tier: - `docs/agent/schema.md`: before you touch persistence: tables, columns, keys and views. - `docs/agent/requirements.md`: before you add or change a capability. diff --git a/server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs index a1f0fddf55..f9c1705d1f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DocsPageConformanceTests.cs @@ -98,4 +98,25 @@ public void Case_rows_data_and_bytes_equal_the_expected_files(string name) foreach (var (path, content) in expectedPages) Assert.True(content == written[path], $"bytes differ for {path}"); } + + // SubDir names the directory the agent pages land in, in place of agent/, as TypeScript's + // agentDocsFile({ subDir }), Python's sub_dir and Rust's subDir do: "llm" writes llm/schema.md, + // never llm/agent/schema.md. + [Fact] + public void SubDirReplacesTheAgentDirectory() + { + string input = Path.Combine(Corpus, "ledger-and-claims", "input"); + var root = Load(input); + var ctx = new GenContext + { + Entities = root.Objects(), + Root = root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme", Dialect = Dialect(input) }, + }; + var expected = new AgentDocsGenerator().Generate(ctx) + .Select(f => "llm/" + f.Path["agent/".Length..]).OrderBy(p => p, StringComparer.Ordinal).ToList(); + Assert.NotEmpty(expected); + Assert.Equal(expected, new AgentDocsGenerator { SubDir = "llm" }.Generate(ctx) + .Select(f => f.Path).OrderBy(p => p, StringComparer.Ordinal).ToList()); + } } diff --git a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs index fecac2f0bd..28e0836b78 100644 --- a/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs +++ b/server/csharp/MetaObjects.Codegen/GeneratorRegistry.cs @@ -349,7 +349,7 @@ private static IGenerator RenderHelper(GeneratorBuildContext ctx) => Tier = GeneratorTier.Neutral, Layer = GeneratorLayer.Docs, Factory = ctx => new AgentDocsGenerator { TemplateRoot = ctx.TemplateRoot }, - Options = "OutDir, SubDir (default \"\"), TemplateRoot (init properties on the entry in codegen/Generators.cs)", + Options = "OutDir, SubDir (default \"agent\"; \"\" writes at the root), TemplateRoot (init properties on the entry in codegen/Generators.cs)", Note = "A model with no requirement gets no requirements page, and one with no table and no view gets no schema page. A project's agent/.mustache under the template root overrides the shipped template.", SourceFileName = "AgentDocsGenerator.cs", Companions = ["Docs/DocsViewPages.cs"], diff --git a/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs index 1052c46711..8c5e678f55 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs @@ -23,8 +23,11 @@ public sealed class AgentDocsGenerator : IGenerator /// The docs output root the pages are written under; null writes under the run's --out. public string? OutDir { get; init; } - /// Where under the pages land; "" writes them at its root. - public string SubDir { get; init; } = ""; + /// The directory under the pages land in, in place of agent; "" writes them at its root. + public string SubDir { get; init; } = DefaultSubDir; + + /// Where the pages land when the entry names no . + public const string DefaultSubDir = "agent"; /// A project template directory: agent/<page>.mustache there overrides the shipped one. public string? TemplateRoot { get; init; } @@ -37,10 +40,10 @@ public IEnumerable Generate(GenContext ctx) var view = DocsView.Build(ctx.Root); // The project chose `meta migrate` (migrate.dialect in .metaobjects/config.json). bool hasMigrate = !string.IsNullOrEmpty(ctx.Config.Dialect); - string prefix = SubDir.TrimEnd('/') is { Length: > 0 } sub ? sub + "/" : ""; + string prefix = SubDir.Trim('/') is { Length: > 0 } sub ? sub + "/" : ""; foreach (var (path, content) in DocsViewPages.Render( view, hasMigrate, TemplateRoot, fqn => imports?.InLedger(fqn) ?? true, includeRequirements: false, includeAgent: true)) - yield return new EmittedFile(prefix + path, content) { WholeModel = true }; + yield return new EmittedFile(prefix + Path.GetFileName(path), content) { WholeModel = true }; } } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java b/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java index 52eeb71ee8..ee4add0743 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java @@ -31,8 +31,10 @@ public final class DocsPagesEmitter { public static final String TOON_PATH = "requirements.toon"; - public static final String AGENT_REQUIREMENTS_PATH = "agent/requirements.md"; - public static final String AGENT_SCHEMA_PATH = "agent/schema.md"; + /** The directory the agent pages land in when the generator names none. */ + public static final String DEFAULT_AGENT_DIR = "agent"; + public static final String AGENT_REQUIREMENTS_PAGE = "requirements.md"; + public static final String AGENT_SCHEMA_PAGE = "schema.md"; private DocsPagesEmitter() { } @@ -101,20 +103,23 @@ public static Map requirementsPages(JsonObject view, String subD return out; } - /** {@code agent/requirements.md} and the model-only {@code agent/schema.md}, each only when the model has one. */ - public static Map agentPages(JsonObject view, boolean hasMigrate, String subDir, Path templateDir, + /** + * {@code requirements.md} and the model-only {@code schema.md}, each only when the model has one, under + * {@code dir} ({@link #DEFAULT_AGENT_DIR} for the standard {@code agent/} pages; empty writes them at the root). + */ + public static Map agentPages(JsonObject view, boolean hasMigrate, String dir, Path templateDir, Predicate inLedger) { Map out = new LinkedHashMap<>(); Provider provider = provider(templateDir); - String prefix = prefix(subDir); + String prefix = prefix(dir); Map requirements = DocsViewPages.agentRequirementsPageData(view, inLedger, ledger -> render(DocsViewPages.REQUIREMENTS_LEDGER_REF, ledger, provider)); if (requirements != null) { - out.put(prefix + AGENT_REQUIREMENTS_PATH, render(DocsViewPages.AGENT_REQUIREMENTS_REF, requirements, provider)); + out.put(prefix + AGENT_REQUIREMENTS_PAGE, render(DocsViewPages.AGENT_REQUIREMENTS_REF, requirements, provider)); } Map schema = DocsViewPages.agentSchemaPageData(view, hasMigrate); if (schema != null) { - out.put(prefix + AGENT_SCHEMA_PATH, + out.put(prefix + AGENT_SCHEMA_PAGE, DocsViewPages.keepOneTrailingNewline(render(DocsViewPages.AGENT_SCHEMA_REF, schema, provider))); } return out; diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java index cffdbb1959..b02b04c664 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java @@ -26,15 +26,15 @@ * {@code agent/ui.md} stays a TypeScript page. No requirement, no requirement page; no table and no * view, no schema page. * - *

    Args: {@code outputDir} (required), {@code subDir} (where under it the pages land, default empty: - * the root) and {@code templateDir} (a directory holding {@code agent/.mustache} and - * {@code requirements/.mustache} overrides). The schema page says to change the schema with + *

    Args: {@code outputDir} (required), {@code subDir} (the directory under it the pages land in, + * default {@code agent}; empty writes them at its root) and {@code templateDir} (a directory holding + * {@code agent/.mustache} and {@code requirements/.mustache} overrides). The schema page says to change the schema with * {@code meta migrate} when the project's {@code .metaobjects/config.json} sets {@code migrate.dialect}. * Give it an {@code outputDir} that holds generated files only.

    */ public class AgentDocsGenerator extends FileEmittingGenerator { - /** Arg: where under {@code outputDir} the pages land. */ + /** Arg: the directory under {@code outputDir} the pages land in, in place of {@code agent}. */ public static final String ARG_SUB_DIR = "subDir"; /** Arg: a directory holding {@code agent/.mustache} that win over the packaged templates. */ @@ -42,7 +42,7 @@ public class AgentDocsGenerator extends FileEmittingGenerator { @Override protected List generate(MetaDataLoader loader) { - String subDir = getArg(ARG_SUB_DIR, ""); + String subDir = getArg(ARG_SUB_DIR, DocsPagesEmitter.DEFAULT_AGENT_DIR); Path templateDir = hasArg(ARG_TEMPLATE_DIR) ? Path.of(getArg(ARG_TEMPLATE_DIR)) : null; JsonObject view = DocsView.build(loader.getRoot()); List files = new ArrayList<>(); diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java index 3a0b88b755..a72c97d31f 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java @@ -109,7 +109,7 @@ public void everyCaseReproducesRowsDataAndBytes() throws IOException { Map agentRequirements = DocsViewPages.agentRequirementsPageData(view, null, ledger -> ""); if (agentRequirements != null) { // The ledger is the rendered embedded template; compare the data through the real renderer. - Map pages = DocsPagesEmitter.agentPages(view, migrate, "", null, null); + Map pages = DocsPagesEmitter.agentPages(view, migrate, DocsPagesEmitter.DEFAULT_AGENT_DIR, null, null); actual.put("data/agent-requirements.md.json", ""); assertTrue(name + ": agent/requirements.md written", pages.containsKey("agent/requirements.md")); } @@ -124,7 +124,7 @@ public void everyCaseReproducesRowsDataAndBytes() throws IOException { // 3. bytes Map pages = new TreeMap<>(); pages.putAll(DocsPagesEmitter.requirementsPages(view, "", null, null)); - pages.putAll(DocsPagesEmitter.agentPages(view, migrate, "", null, null)); + pages.putAll(DocsPagesEmitter.agentPages(view, migrate, DocsPagesEmitter.DEFAULT_AGENT_DIR, null, null)); actual.putAll(pages); // The agent requirements data carries the rendered ledger: check it against the pinned data too. diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt index d6bde43274..fef227226e 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt @@ -22,13 +22,13 @@ import java.nio.file.Path * page says to change the schema with `meta migrate` when the project's `.metaobjects/config.json` sets * `migrate.dialect`. * - * Args: `outputDir` (required), `subDir` (where under it the pages land, default empty: the root) and - * `templateDir` (a directory holding `agent/.mustache` and `requirements/.mustache` overrides). + * Args: `outputDir` (required), `subDir` (the directory under it the pages land in, default `agent`; empty + * writes them at its root) and `templateDir` (a directory holding `agent/.mustache` and `requirements/.mustache` overrides). */ open class KotlinAgentDocsGenerator : FileEmittingGenerator() { override fun generate(loader: MetaDataLoader): List { - val subDir = getArg(ARG_SUB_DIR, "") + val subDir = getArg(ARG_SUB_DIR, DocsPagesEmitter.DEFAULT_AGENT_DIR) val templateDir: Path? = if (hasArg(ARG_TEMPLATE_DIR)) Path.of(getArg(ARG_TEMPLATE_DIR)) else null val view = DocsView.build(loader.root) return DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, DocsPagesEmitter.inLedger(loader)) diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementPagesLedgerTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementPagesLedgerTest.kt index 32dcdd3c37..495e47a860 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementPagesLedgerTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinRequirementPagesLedgerTest.kt @@ -145,4 +145,23 @@ class KotlinRequirementPagesLedgerTest { @Test fun `a scope include naming the dependency lists none of its requirements`() = assertPagesListTheLedger("a-scope-include-naming-the-package-does-not-inherit-its-requirements") + + /** + * `subDir` names the directory the agent pages land in, in place of `agent`, as the TypeScript + * `agentDocsFile({ subDir })`, Python `AgentDocsGenerator(sub_dir=...)` and Rust `agent-docs` + * options do: `llm` writes `llm/schema.md`, never `llm/agent/schema.md`. + */ + @Test fun `subDir replaces the agent directory`() { + val loader = load(case("an-own-requirement-beside-an-uninherited-dependency-ledger-is-the-whole-ledger")) + val out = tempDir("kreq-ledger-subdir-") + GeneratedFileWriter.beginRun().use { run -> + val gen = KotlinAgentDocsGenerator() + run.attributeTo(gen.javaClass.simpleName) + gen.setArgs(mapOf("outputDir" to out.toString(), "subDir" to "llm")).execute(loader) + } + val written = Files.walk(out).use { s -> + s.filter { Files.isRegularFile(it) }.map { out.relativize(it).toString().replace('\\', '/') }.toList().toSet() + } + assertTrue(written == setOf("llm/requirements.md", "llm/schema.md"), "written: $written") + } } diff --git a/server/python/src/metaobjects/agent_context/shipped/files/527e422aeec9a36d.md b/server/python/src/metaobjects/agent_context/shipped/files/527e422aeec9a36d.md deleted file mode 100644 index 579a3509ae..0000000000 --- a/server/python/src/metaobjects/agent_context/shipped/files/527e422aeec9a36d.md +++ /dev/null @@ -1,7 +0,0 @@ -## Pages generated for this project - -`meta gen` writes these from the metadata (they are regenerated output, like the code). Read the -one for a tier before you change that tier: - -{{pageList}} - diff --git a/server/python/src/metaobjects/agent_context/shipped/files/5497499d5dddc2cc.md b/server/python/src/metaobjects/agent_context/shipped/files/5497499d5dddc2cc.md new file mode 100644 index 0000000000..bf233c2a66 --- /dev/null +++ b/server/python/src/metaobjects/agent_context/shipped/files/5497499d5dddc2cc.md @@ -0,0 +1,7 @@ +## Pages generated for this project + +The project's `gen` command writes these from the metadata (they are regenerated output, like the +code). Read the one for a tier before you change that tier: + +{{pageList}} + diff --git a/server/python/src/metaobjects/agent_context/shipped/manifest.json b/server/python/src/metaobjects/agent_context/shipped/manifest.json index bf05f04901..ca50485056 100644 --- a/server/python/src/metaobjects/agent_context/shipped/manifest.json +++ b/server/python/src/metaobjects/agent_context/shipped/manifest.json @@ -3,7 +3,7 @@ "docsRef": "main", "docsLinkPrefix": "https://github.com/metaobjectsdev/metaobjects/blob/", "skillsDir": ".claude/skills", - "agentPagesTemplate": "527e422aeec9a36d.md", + "agentPagesTemplate": "5497499d5dddc2cc.md", "stacks": [ { "id": "typescript", From 666fec23494c00a64fc3a850489f8cd3835af74c Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 09:08:17 -0500 Subject: [PATCH 19/21] no-mistakes(test): Agent schema page drops imported nodes in every port --- changelog.d/agent-pages-every-port.md | 8 ++- .../MetaObjects.Codegen/Docs/DocsViewPages.cs | 14 ++--- .../Generators/AgentDocsGenerator.cs | 4 +- .../docs/pages/DocsPagesEmitter.java | 21 +++++++- .../metaobjects/docs/pages/DocsViewPages.java | 14 +++-- .../generator/AgentDocsGenerator.java | 3 +- .../docs/pages/DocsPageConformanceTest.java | 6 +-- .../kotlin/KotlinAgentDocsGenerator.kt | 3 +- .../KotlinDependencyImportExclusionTest.kt | 10 +++- .../spring/DependencyImportExclusionTest.java | 11 +++- .../src/metaobjects/codegen/generator.py | 5 ++ .../generators/agent_docs_generator.py | 2 +- .../python/src/metaobjects/codegen/runner.py | 1 + .../codegen/runtime/docs_schema.py | 18 +++++-- .../tests/codegen/test_cli_dependencies.py | 14 ++++- .../metaobjects-codegen/src/agent_docs.rs | 8 ++- .../metaobjects-codegen/src/docs_pages.rs | 20 +++++--- .../tests/docs_page_conformance.rs | 2 +- .../tests/reference_nodes.rs | 51 ++++++++++++++++++- .../cli/test/gen-imported-nodes.test.ts | 38 +++++++++++++- .../src/generators/agent-docs-file.ts | 7 ++- .../src/generators/agent-schema-page.ts | 36 +++++++++---- .../src/generators/docs-view-pages.ts | 23 +++++++-- .../codegen-ts/src/reference/agent-docs.ts | 7 ++- .../packages/codegen-ts/test/run-gen.test.ts | 28 ++++++++++ 25 files changed, 294 insertions(+), 60 deletions(-) diff --git a/changelog.d/agent-pages-every-port.md b/changelog.d/agent-pages-every-port.md index c629306c2b..69dc1ebe58 100644 --- a/changelog.d/agent-pages-every-port.md +++ b/changelog.d/agent-pages-every-port.md @@ -5,8 +5,12 @@ `templates/requirements/` and `templates/agent/` Mustache pages, byte for byte what `fixtures/docs-page-conformance/` pins. A TypeScript project with no dialect now gets the model-only `agent/schema.md` too (it used to get no schema page); with a dialect it keeps the - physical page. `agent/ui.md` stays TypeScript's. Rust has no requirement ledger of its own - yet, so its pages list every requirement the view carries, an uninherited import's included. + physical page. `agent/schema.md` documents the project's own storage in every port: a + dependency's object that `scope.include` does not name is left out of its tables, views, + relationships and enums (Rust loads no dependency, and leaves out a reference node). The + TypeScript physical page used to list an imported table too. `agent/ui.md` stays + TypeScript's. Rust has no requirement ledger of its own yet, so its pages list every + requirement the view carries, an uninherited import's included. The docs view gains a `storage` section (`docs/features/docs-view.md`): every table and view the model stores into, its columns (names from the port's naming helpers, each linked to its diff --git a/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs b/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs index 5ec3753546..fa63fb7a8e 100644 --- a/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs +++ b/server/csharp/MetaObjects.Codegen/Docs/DocsViewPages.cs @@ -405,11 +405,13 @@ private static string JsText(JsonNode? n) => /// view alone. : the project chose a meta migrate dialect /// (migrate.dialect in .metaobjects/config.json). Null when the model declares no table /// and no view: no page. - public static Dictionary? AgentSchemaData(JsonObject view, bool hasMigrate) + public static Dictionary? AgentSchemaData(JsonObject view, bool hasMigrate, Func? inScope = null) { var storage = Obj(view["storage"]); - var tables = Objs(storage["tables"]).ToList(); - var views = Objs(storage["views"]).ToList(); + // A dependency's node the project did not take into scope is not the project's schema. + bool Scoped(string id) => inScope is null || inScope(id); + var tables = Objs(storage["tables"]).Where(t => Scoped(Str(Obj(t["declaredBy"])["id"]))).ToList(); + var views = Objs(storage["views"]).Where(v => Scoped(Str(Obj(v["declaredBy"])["id"]))).ToList(); if (tables.Count == 0 && views.Count == 0) return null; var members = MembersById(view); string FieldName(string id) => members.TryGetValue(id, out var m) ? Str(m["name"]) : ""; @@ -473,7 +475,7 @@ private static string JsText(JsonNode? n) => var relationships = new List(); foreach (var n in byOrder) { - if (Str(n["type"]) != "object") continue; + if (Str(n["type"]) != "object" || !Scoped(Str(n["id"]))) continue; foreach (var rel in DirectMembers(n, "relationship")) { string? through = AttrText(rel, "through"); @@ -565,7 +567,7 @@ private static string RenderTemplate(string text, object data) => /// requirements and the agent-docs generator's pages. public static IEnumerable<(string Path, string Content)> Render( JsonObject view, bool hasMigrate, string? templateRoot, Func? inLedger, - bool includeRequirements, bool includeAgent) + bool includeRequirements, bool includeAgent, Func? inScope = null) { var rows = RequirementRows(view, inLedger); if (includeRequirements && rows.Count > 0) @@ -575,7 +577,7 @@ private static string RenderTemplate(string text, object data) => view, RenderTemplate(Template("requirements", LedgerTemplate, templateRoot), LedgerData(rows, embedded: true)), inLedger); if (data is not null) yield return (AgentRequirementsPath, RenderTemplate(Template("agent", AgentRequirementsTemplate, templateRoot), data)); - if (AgentSchemaData(view, hasMigrate) is { } schema) + if (AgentSchemaData(view, hasMigrate, inScope) is { } schema) yield return (AgentSchemaPath, RenderTemplate(Template("agent", AgentSchemaTemplate, templateRoot), schema).TrimEnd('\n') + "\n"); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs index 8c5e678f55..6ac039295d 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/AgentDocsGenerator.cs @@ -40,10 +40,12 @@ public IEnumerable Generate(GenContext ctx) var view = DocsView.Build(ctx.Root); // The project chose `meta migrate` (migrate.dialect in .metaobjects/config.json). bool hasMigrate = !string.IsNullOrEmpty(ctx.Config.Dialect); + // An object a dependency brought and the project did not take into scope is left out of the schema. + var inScope = ctx.Root.Objects().Where(ctx.Root.InScope).Select(o => o.ResolutionKey()).ToHashSet(StringComparer.Ordinal); string prefix = SubDir.Trim('/') is { Length: > 0 } sub ? sub + "/" : ""; foreach (var (path, content) in DocsViewPages.Render( view, hasMigrate, TemplateRoot, fqn => imports?.InLedger(fqn) ?? true, - includeRequirements: false, includeAgent: true)) + includeRequirements: false, includeAgent: true, inScope.Contains)) yield return new EmittedFile(prefix + Path.GetFileName(path), content) { WholeModel = true }; } } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java b/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java index ee4add0743..3da7eda56b 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsPagesEmitter.java @@ -3,16 +3,20 @@ import com.google.gson.JsonObject; import com.metaobjects.config.DependencySet; import com.metaobjects.docs.metamodel.MetamodelDocsEmitter; +import com.metaobjects.generator.util.GeneratorUtil; import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.object.MetaObject; import com.metaobjects.render.Escapers; import com.metaobjects.render.Provider; import com.metaobjects.render.RenderRequest; import com.metaobjects.render.Renderer; import java.nio.file.Path; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -92,6 +96,18 @@ public static Predicate inLedger(MetaDataLoader loader) { return deps.isEmpty() ? null : deps::inLedger; } + /** + * The objects that are this project's own to document in its schema: not a dependency's object + * outside {@code scope.include}, and not a reference node ({@link GeneratorUtil#isImported}). + * Null when nothing is imported: every object in the view is the project's own. + */ + public static Predicate inScope(MetaDataLoader loader) { + List objects = loader.getMetaObjects(); + Set own = new HashSet<>(); + for (MetaObject o : GeneratorUtil.ownMetaObjects(loader)) own.add(o.getName()); + return own.size() == objects.size() ? null : own::contains; + } + /** {@code requirements.toon}, or nothing for an empty ledger. Keyed by path relative to {@code subDir}. */ public static Map requirementsPages(JsonObject view, String subDir, Path templateDir, Predicate inLedger) { @@ -106,9 +122,10 @@ public static Map requirementsPages(JsonObject view, String subD /** * {@code requirements.md} and the model-only {@code schema.md}, each only when the model has one, under * {@code dir} ({@link #DEFAULT_AGENT_DIR} for the standard {@code agent/} pages; empty writes them at the root). + * {@code inLedger} filters the requirements ({@link #inLedger}); {@code inScope} the schema's objects ({@link #inScope}). */ public static Map agentPages(JsonObject view, boolean hasMigrate, String dir, Path templateDir, - Predicate inLedger) { + Predicate inLedger, Predicate inScope) { Map out = new LinkedHashMap<>(); Provider provider = provider(templateDir); String prefix = prefix(dir); @@ -117,7 +134,7 @@ public static Map agentPages(JsonObject view, boolean hasMigrate if (requirements != null) { out.put(prefix + AGENT_REQUIREMENTS_PAGE, render(DocsViewPages.AGENT_REQUIREMENTS_REF, requirements, provider)); } - Map schema = DocsViewPages.agentSchemaPageData(view, hasMigrate); + Map schema = DocsViewPages.agentSchemaPageData(view, hasMigrate, inScope); if (schema != null) { out.put(prefix + AGENT_SCHEMA_PAGE, DocsViewPages.keepOneTrailingNewline(render(DocsViewPages.AGENT_SCHEMA_REF, schema, provider))); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsViewPages.java b/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsViewPages.java index 6f003660a4..8131911597 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsViewPages.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/docs/pages/DocsViewPages.java @@ -490,12 +490,16 @@ private static String cardinalityPhrase(JsonElement cardinality, String through) /** * The data {@code agent/schema.md.mustache} renders for the model-only page, built from the view * alone. {@code hasMigrate}: the project chose a {@code meta migrate} dialect. Null when the model - * declares no table and no view: no page. + * declares no table and no view: no page. {@code inScope} keeps only the objects that are the + * project's own (null keeps every object): a dependency's object is not the project's schema. */ - public static Map agentSchemaPageData(JsonObject view, boolean hasMigrate) { + public static Map agentSchemaPageData(JsonObject view, boolean hasMigrate, Predicate inScope) { JsonObject storage = view.getAsJsonObject("storage"); - List tables = objects(arr(storage, "tables")); - List views = objects(arr(storage, "views")); + Predicate scoped = inScope == null ? id -> true : inScope; + List tables = new ArrayList<>(); + for (JsonObject t : objects(arr(storage, "tables"))) if (scoped.test(str(t.getAsJsonObject("declaredBy"), "id"))) tables.add(t); + List views = new ArrayList<>(); + for (JsonObject v : objects(arr(storage, "views"))) if (scoped.test(str(v.getAsJsonObject("declaredBy"), "id"))) views.add(v); if (tables.isEmpty() && views.isEmpty()) return null; Map members = membersById(view); List byOrder = new ArrayList<>(objects(arr(view, "nodes"))); @@ -569,7 +573,7 @@ public static Map agentSchemaPageData(JsonObject view, boolean h // Every relationship as written, in declaration order of its object. List relationships = new ArrayList<>(); for (JsonObject n : byOrder) { - if (!TYPE_OBJECT.equals(str(n, "type"))) continue; + if (!TYPE_OBJECT.equals(str(n, "type")) || !scoped.test(str(n, "id"))) continue; for (JsonObject rel : directMembers(n, TYPE_RELATIONSHIP)) { String through = attrText(rel, "through"); String onDelete = attrText(rel, "onDelete"); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java index b02b04c664..ee30218b92 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/AgentDocsGenerator.java @@ -46,7 +46,8 @@ protected List generate(MetaDataLoader loader) { Path templateDir = hasArg(ARG_TEMPLATE_DIR) ? Path.of(getArg(ARG_TEMPLATE_DIR)) : null; JsonObject view = DocsView.build(loader.getRoot()); List files = new ArrayList<>(); - for (Map.Entry page : DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, DocsPagesEmitter.inLedger(loader)).entrySet()) { + for (Map.Entry page : DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, + DocsPagesEmitter.inLedger(loader), DocsPagesEmitter.inScope(loader)).entrySet()) { files.add(new EmittedFile(page.getKey(), page.getValue())); } return files; diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java index a72c97d31f..fd350feb3d 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/docs/pages/DocsPageConformanceTest.java @@ -109,11 +109,11 @@ public void everyCaseReproducesRowsDataAndBytes() throws IOException { Map agentRequirements = DocsViewPages.agentRequirementsPageData(view, null, ledger -> ""); if (agentRequirements != null) { // The ledger is the rendered embedded template; compare the data through the real renderer. - Map pages = DocsPagesEmitter.agentPages(view, migrate, DocsPagesEmitter.DEFAULT_AGENT_DIR, null, null); + Map pages = DocsPagesEmitter.agentPages(view, migrate, DocsPagesEmitter.DEFAULT_AGENT_DIR, null, null, null); actual.put("data/agent-requirements.md.json", ""); assertTrue(name + ": agent/requirements.md written", pages.containsKey("agent/requirements.md")); } - Map schema = DocsViewPages.agentSchemaPageData(view, migrate); + Map schema = DocsViewPages.agentSchemaPageData(view, migrate, null); if (schema != null) { assertJson(name + " rows/schema.json", expected.get("rows/schema.json"), DocsViewPages.schemaRows(view)); assertJson(name + " data/agent-schema.md.json", expected.get("data/agent-schema.md.json"), schema); @@ -124,7 +124,7 @@ public void everyCaseReproducesRowsDataAndBytes() throws IOException { // 3. bytes Map pages = new TreeMap<>(); pages.putAll(DocsPagesEmitter.requirementsPages(view, "", null, null)); - pages.putAll(DocsPagesEmitter.agentPages(view, migrate, DocsPagesEmitter.DEFAULT_AGENT_DIR, null, null)); + pages.putAll(DocsPagesEmitter.agentPages(view, migrate, DocsPagesEmitter.DEFAULT_AGENT_DIR, null, null, null)); actual.putAll(pages); // The agent requirements data carries the rendered ledger: check it against the pinned data too. diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt index fef227226e..2f41db76da 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinAgentDocsGenerator.kt @@ -31,7 +31,8 @@ open class KotlinAgentDocsGenerator : FileEmittingGenerator() { val subDir = getArg(ARG_SUB_DIR, DocsPagesEmitter.DEFAULT_AGENT_DIR) val templateDir: Path? = if (hasArg(ARG_TEMPLATE_DIR)) Path.of(getArg(ARG_TEMPLATE_DIR)) else null val view = DocsView.build(loader.root) - return DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, DocsPagesEmitter.inLedger(loader)) + return DocsPagesEmitter.agentPages(view, choseMigrateDialect(loader), subDir, templateDir, + DocsPagesEmitter.inLedger(loader), DocsPagesEmitter.inScope(loader)) .map { (path, content) -> EmittedFile(path, content) } } diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDependencyImportExclusionTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDependencyImportExclusionTest.kt index b888c8161b..6a75328763 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDependencyImportExclusionTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDependencyImportExclusionTest.kt @@ -69,7 +69,7 @@ class KotlinDependencyImportExclusionTest { KotlinEntityGenerator(), KotlinExposedTableGenerator(), KotlinRelationsGenerator(), KotlinRepositoryGenerator(), KotlinNamesGenerator(), KotlinFilterAllowlistGenerator(), KotlinSpringControllerGenerator(), KotlinReportExportGenerator(), - KotlinStoredProcGenerator(), KotlinExtractorGenerator(), + KotlinStoredProcGenerator(), KotlinExtractorGenerator(), KotlinAgentDocsGenerator(), ) GeneratedFileWriter.beginRun().use { run -> for (gen in generators) { @@ -81,6 +81,14 @@ class KotlinDependencyImportExclusionTest { val files = Files.walk(outDir).use { s -> s.filter { Files.isRegularFile(it) }.toList() } assertTrue(files.any { it.fileName.toString().startsWith("Order") }, "the project's own Order must still generate: $files") + // agent/schema.md documents the project's own storage: the local Order, never an imported table. + val schema = outDir.resolve("agent/schema.md") + assertTrue(Files.isRegularFile(schema), "agent-docs writes the project's schema page: $files") + val schemaBody = Files.readString(schema) + assertTrue("app::Order" in schemaBody, "agent/schema.md names the local Order") + for (imported in listOf("Customer", "Address", "Audited", "acme::common")) { + assertFalse(imported in schemaBody, "agent/schema.md names the imported $imported") + } for (f in files) { val rel = outDir.relativize(f).toString() assertFalse("acme" in rel || "Customer" in rel || "Address" in rel, diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/DependencyImportExclusionTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/DependencyImportExclusionTest.java index 107fcaca80..dfc8c10780 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/DependencyImportExclusionTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/DependencyImportExclusionTest.java @@ -4,6 +4,7 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.metaobjects.config.DependencySet; +import com.metaobjects.generator.AgentDocsGenerator; import com.metaobjects.generator.Generator; import com.metaobjects.generator.direct.object.javacode.ExtractorCodeGenerator; import com.metaobjects.generator.direct.object.javacode.JavaObjectCodeGenerator; @@ -102,7 +103,7 @@ public void noGeneratorEmitsForAnImportedNode() throws Exception { new SpringNamesGenerator(), new SpringControllerGenerator(), new SpringReportExportGenerator(), new LlmTraceHelperGenerator(), new SpringOutputParserGenerator(), new SpringOutputPromptGenerator(), - new SpringRenderHelperGenerator()); + new SpringRenderHelperGenerator(), new AgentDocsGenerator()); try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { for (Generator gen : generators) { run.attributeTo(gen.getClass().getSimpleName()); @@ -118,6 +119,14 @@ public void noGeneratorEmitsForAnImportedNode() throws Exception { } assertTrue("the project's own Order must still generate: " + files, files.stream().anyMatch(p -> p.getFileName().toString().startsWith("Order"))); + // agent/schema.md documents the project's own storage: the local Order, never an imported table. + Path schema = outDir.resolve("agent/schema.md"); + assertTrue("agent-docs writes the project's schema page: " + files, Files.isRegularFile(schema)); + String schemaBody = Files.readString(schema, StandardCharsets.UTF_8); + assertTrue("agent/schema.md names the local Order", schemaBody.contains("app::Order")); + for (String imported : List.of("Customer", "Address", "Audited", "acme::common")) { + assertFalse("agent/schema.md names the imported " + imported, schemaBody.contains(imported)); + } for (Path f : files) { String rel = outDir.relativize(f).toString(); assertFalse("a file was emitted for an imported node: " + rel, diff --git a/server/python/src/metaobjects/codegen/generator.py b/server/python/src/metaobjects/codegen/generator.py index 90eec55aee..fb8aa97fe2 100644 --- a/server/python/src/metaobjects/codegen/generator.py +++ b/server/python/src/metaobjects/codegen/generator.py @@ -44,6 +44,11 @@ class GenContext: #: (``Collection.in_ledger``)? A dependency's requirement the project did not inherit #: gets no generated test. ``None``: every loaded requirement is the project's. in_ledger: Callable[[str], bool] | None = None + #: FR-023 — is the object at this resolution key the project's own to generate + #: (``run_gen``'s ``select``, normally ``Collection.in_scope``)? A whole-model page built + #: from the docs view reads it to leave a dependency's objects out. ``None``: every + #: loaded object is the project's. + in_scope: Callable[[str], bool] | None = None #: The run's one claim registry : a generator claims each module it emits in #: its generated package directory, and a second claimant is refused with #: ``ERR_NAME_COLLISION``. ``run_gen`` shares one across every generator of the run. diff --git a/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py b/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py index 3e2fdc4aa1..11cbfbe758 100644 --- a/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py +++ b/server/python/src/metaobjects/codegen/generators/agent_docs_generator.py @@ -59,7 +59,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: # `.metaobjects/config.json` is already part of the run's skip key (cli `_skip_identity`). has_migrate = chose_migrate_dialect(ctx.config.project_root) - schema_data = agent_schema_page_data(view, has_migrate) + schema_data = agent_schema_page_data(view, has_migrate, ctx.in_scope) if schema_data is not None: path = f"{self._dir}/schema.md" page = render_doc_page(AGENT_SCHEMA_PAGE_REF, schema_data, self._provider, path) diff --git a/server/python/src/metaobjects/codegen/runner.py b/server/python/src/metaobjects/codegen/runner.py index b7e8794795..dcff866f35 100644 --- a/server/python/src/metaobjects/codegen/runner.py +++ b/server/python/src/metaobjects/codegen/runner.py @@ -252,6 +252,7 @@ def is_selected(o: MetaObject) -> bool: warn=_warn_collector(gen.name, result.warnings), generators=tuple(g.name for g in generators), in_ledger=in_ledger, + in_scope=select, claims=claims, selected=is_selected if narrowed else None, run_provenance=( diff --git a/server/python/src/metaobjects/codegen/runtime/docs_schema.py b/server/python/src/metaobjects/codegen/runtime/docs_schema.py index 5983581a74..8f593d8920 100644 --- a/server/python/src/metaobjects/codegen/runtime/docs_schema.py +++ b/server/python/src/metaobjects/codegen/runtime/docs_schema.py @@ -13,7 +13,7 @@ from __future__ import annotations import re -from typing import Any +from typing import Any, Callable from .docs_requirements import GENERATED_MARKER @@ -166,12 +166,20 @@ def _cardinality_phrase(cardinality: Any, through: str | None) -> str: return "cardinality not declared" -def agent_schema_page_data(view: Json, has_migrate: bool = False) -> Json | None: +def agent_schema_page_data( + view: Json, has_migrate: bool = False, in_scope: Callable[[str], bool] | None = None +) -> Json | None: """The data ``agent/schema.md.mustache`` renders (``physical: false``), built from the docs view alone. ``has_migrate``: the project chose a ``meta migrate`` dialect (``metaobjects.config.neutral_config.chose_migrate_dialect``). ``None`` when the model - declares no table and no view: no page.""" - tables, views = view["storage"]["tables"], view["storage"]["views"] + declares no table and no view: no page. ``in_scope`` keeps only the project's own objects + (``None`` keeps every object): a dependency's object is not the project's schema.""" + + def scoped(node_id: str) -> bool: + return in_scope is None or in_scope(node_id) + + tables = [t for t in view["storage"]["tables"] if scoped(t["declaredBy"]["id"])] + views = [v for v in view["storage"]["views"] if scoped(v["declaredBy"]["id"])] if not tables and not views: return None members = _members_by_id(view) @@ -225,7 +233,7 @@ def agent_schema_page_data(view: Json, has_migrate: bool = False) -> Json | None # Every relationship as written, in declaration order of its object. relationships: list[str] = [] for n in by_order: - if n["type"] != _TYPE_OBJECT: + if n["type"] != _TYPE_OBJECT or not scoped(n["id"]): continue for rel in _direct_members(n, _TYPE_RELATIONSHIP): through = _attr_text(rel["attrs"], "through") diff --git a/server/python/tests/codegen/test_cli_dependencies.py b/server/python/tests/codegen/test_cli_dependencies.py index b0b0d75c3f..0a6939425d 100644 --- a/server/python/tests/codegen/test_cli_dependencies.py +++ b/server/python/tests/codegen/test_cli_dependencies.py @@ -55,6 +55,7 @@ def _consumer( *, scope_include: list[str] | None = None, target_entities: list[str] | None = None, + generators: str = "names", ) -> Path: """A consumer project: APP + SNAP + CONFIG_REF + LOCK_V1, with one `metaobjects.config.yaml` target (`generators: [names]`).""" @@ -82,7 +83,7 @@ def _consumer( "targets:\n" " main:\n" " outDir: gen\n" - f" generators: [names]{entities_line}\n" + f" generators: [{generators}]{entities_line}\n" ) return tmp_path / "metaobjects.config.yaml" @@ -95,6 +96,17 @@ def test_gen_excludes_the_dependencys_entities_by_default(tmp_path: Path) -> Non assert not (tmp_path / "gen" / "customer_names.py").exists() +def test_agent_schema_page_leaves_the_dependencys_objects_out(tmp_path: Path) -> None: + # agent/schema.md documents the project's own storage: the local Order, never an import. + cfg = _consumer(tmp_path, generators="agent-docs") + rc = main(["gen", "--config", str(cfg)]) + assert rc == 0 + schema = (tmp_path / "gen" / "agent" / "schema.md").read_text() + assert "app::Order" in schema + for imported in ("Customer", "Address", "Audited", "acme::common"): + assert imported not in schema, imported + + def test_gen_scope_include_naming_the_package_opts_it_in(tmp_path: Path) -> None: cfg = _consumer(tmp_path, scope_include=["acme::common::**"]) rc = main(["gen", "--config", str(cfg)]) diff --git a/server/rust/metaobjects-codegen/src/agent_docs.rs b/server/rust/metaobjects-codegen/src/agent_docs.rs index 731964764f..8d84512c75 100644 --- a/server/rust/metaobjects-codegen/src/agent_docs.rs +++ b/server/rust/metaobjects-codegen/src/agent_docs.rs @@ -110,7 +110,13 @@ fn pages_under(dir: &str, ctx: &GenContext<'_>) -> Result, GenE let templates = DocsTemplates::new(ctx); let mut files = Vec::new(); let path = at("schema.md"); - if let Some(page) = agent_schema_page(&view, has_migrate(ctx), &templates, &path)? { + if let Some(page) = agent_schema_page( + &view, + has_migrate(ctx), + ctx.reference_nodes, + &templates, + &path, + )? { files.push(EmittedFile::new(path, page)); } let path = at("requirements.md"); diff --git a/server/rust/metaobjects-codegen/src/docs_pages.rs b/server/rust/metaobjects-codegen/src/docs_pages.rs index 0b79a1628b..394bc2736f 100644 --- a/server/rust/metaobjects-codegen/src/docs_pages.rs +++ b/server/rust/metaobjects-codegen/src/docs_pages.rs @@ -16,7 +16,7 @@ //! every `requirement.*` node of the model, and a dependency's requirement the project did not //! inherit is not left out. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use metaobjects::docs_view; use metaobjects::naming::NamingRegistry; @@ -626,10 +626,17 @@ fn cardinality_phrase(cardinality: Option<&Value>, through: bool) -> &'static st /// The data `agent/schema.md.mustache` renders for the model-only page, built from the view /// alone. `has_migrate`: the project chose a `meta migrate` dialect (`migrate.dialect` in /// `.metaobjects/config.json`). `None` when the model declares no table and no view: no page. -pub fn agent_schema_page_data(view: &Value, has_migrate: bool) -> Option { +/// `not_own` names the objects that are another run's to generate (the run's reference nodes): +/// they are not the project's schema, so the page leaves them out. +pub fn agent_schema_page_data( + view: &Value, + has_migrate: bool, + not_own: &BTreeSet, +) -> Option { let storage = &view["storage"]; - let tables = arr(storage, "tables"); - let views = arr(storage, "views"); + let own = |v: &&Value| !not_own.contains(s(&v["declaredBy"], "id")); + let tables: Vec<&Value> = arr(storage, "tables").iter().filter(own).collect(); + let views: Vec<&Value> = arr(storage, "views").iter().filter(own).collect(); if tables.is_empty() && views.is_empty() { return None; } @@ -728,7 +735,7 @@ pub fn agent_schema_page_data(view: &Value, has_migrate: bool) -> Option // Every relationship as written, in declaration order of its object. let mut relationships: Vec = Vec::new(); for n in &by_order { - if s(n, "type") != "object" { + if s(n, "type") != "object" || not_own.contains(s(n, "id")) { continue; } for rel in direct_members(n, "relationship") { @@ -938,10 +945,11 @@ pub fn agent_requirements_page( pub fn agent_schema_page( view: &Value, has_migrate: bool, + not_own: &BTreeSet, templates: &DocsTemplates, path: &str, ) -> Result, GenError> { - match agent_schema_page_data(view, has_migrate) { + match agent_schema_page_data(view, has_migrate, not_own) { Some(data) => { let page = render_doc_page(AGENT_SCHEMA_PAGE_REF, &data, templates, path)?; Ok(Some(end_with_one_newline(&page))) diff --git a/server/rust/metaobjects-codegen/tests/docs_page_conformance.rs b/server/rust/metaobjects-codegen/tests/docs_page_conformance.rs index 77834016d6..ba7aeecd0b 100644 --- a/server/rust/metaobjects-codegen/tests/docs_page_conformance.rs +++ b/server/rust/metaobjects-codegen/tests/docs_page_conformance.rs @@ -97,7 +97,7 @@ fn built(view: &Value, has_migrate: bool) -> BTreeMap { if let Some(d) = agent_requirements_page_data(view, ledger).unwrap() { out.insert("data/agent-requirements.md.json".into(), d); } - if let Some(d) = agent_schema_page_data(view, has_migrate) { + if let Some(d) = agent_schema_page_data(view, has_migrate, &Default::default()) { out.insert("data/agent-schema.md.json".into(), d); out.insert("rows/schema.json".into(), schema_rows(view)); } diff --git a/server/rust/metaobjects-codegen/tests/reference_nodes.rs b/server/rust/metaobjects-codegen/tests/reference_nodes.rs index 4d64896b9c..abd4f765b6 100644 --- a/server/rust/metaobjects-codegen/tests/reference_nodes.rs +++ b/server/rust/metaobjects-codegen/tests/reference_nodes.rs @@ -6,7 +6,7 @@ mod common; use common::Scratch; use metaobjects_codegen::generator::GenContext; use metaobjects_codegen::project::load_project; -use metaobjects_codegen::{EntityGenerator, Generator}; +use metaobjects_codegen::{AgentDocsGenerator, EntityGenerator, Generator}; const CONFIG: &str = r#"{ "schema_version": 1, "sources": [ { "path": "model" }, { "path": "replies", "reference": true } ] }"#; @@ -61,3 +61,52 @@ fn a_reference_node_is_loaded_and_not_generated() { "the reference value object is not emitted:\n{all}" ); } + +const OWN_TABLES: &str = r#"{ "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Ticket", "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } + ] } } +] } }"#; + +const REPLY_TABLES: &str = r#"{ "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Archive", "children": [ + { "source.rdb": { "@table": "archives" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } } + ] } } +] } }"#; + +#[test] +fn the_agent_schema_page_leaves_a_reference_node_out() { + // agent/schema.md documents the project's own storage; a reference node is another run's. + let project = Scratch::project( + "reference-schema", + &[ + (".metaobjects/config.json", CONFIG), + ("model/meta.own.json", OWN_TABLES), + ("replies/meta.replies.json", REPLY_TABLES), + ], + ); + let loaded = load_project(project.path(), None, false).expect("the model loads clean"); + let ctx = GenContext { + tree: &loaded.result.tree, + root: loaded.result.root, + entities: &[], + collection: &loaded.collection, + reference_nodes: &loaded.reference_nodes, + generated_files: None, + }; + let files = AgentDocsGenerator.generate(&ctx).expect("generates"); + let schema = files + .iter() + .find(|f| f.path == "agent/schema.md") + .expect("agent-docs writes the schema page"); + assert!(schema.content.contains("acme::Ticket"), "the project's own table is listed"); + assert!( + !schema.content.contains("Archive") && !schema.content.contains("archives"), + "the reference node's table is not listed:\n{}", + schema.content + ); +} diff --git a/server/typescript/packages/cli/test/gen-imported-nodes.test.ts b/server/typescript/packages/cli/test/gen-imported-nodes.test.ts index 3bb1da55c2..aa9a25ffcb 100644 --- a/server/typescript/packages/cli/test/gen-imported-nodes.test.ts +++ b/server/typescript/packages/cli/test/gen-imported-nodes.test.ts @@ -12,7 +12,7 @@ // dependency-conformance corpus (fixtures/dependency-conformance/) uses for // "a-dependency-adds-its-artifact-to-the-resolved-set". import { describe, test, expect, beforeEach, afterEach } from "bun:test"; -import { mkdtempSync, mkdirSync, rmSync, readdirSync, writeFileSync } from "node:fs"; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, readdirSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { METAMODEL_VERSION } from "@metaobjectsdev/metadata"; @@ -74,7 +74,7 @@ function genOutDir(root: string): string { } /** Scaffold a consumer of `acme-common`, optionally declaring `scope.include`. */ -function setupRepo(opts: { scopeInclude?: string[] } = {}): string { +function setupRepo(opts: { scopeInclude?: string[]; agentDocs?: boolean } = {}): string { mkdirSync(WORKSPACE_TMP, { recursive: true }); const root = mkdtempSync(join(WORKSPACE_TMP, "forge-gen-imported-")); @@ -115,6 +115,25 @@ function setupRepo(opts: { scopeInclude?: string[] } = {}): string { "utf8", ); + if (opts.agentDocs === true) { + writeFileSync( + join(root, "metaobjects.config.ts"), + ` +import { defineConfig } from "@metaobjectsdev/codegen-ts"; +import { agentDocsFile } from "@metaobjectsdev/codegen-ts/generators"; +export default defineConfig({ + outDir: ${JSON.stringify(genOutDir(root))}, + outputLayout: "flat", + dialect: "sqlite", + dbImport: "~/db", + extStyle: "none", + targets: { docs: { outDir: ${JSON.stringify(join(root, "docs"))} } }, + generators: [agentDocsFile()], +}); +`, + ); + return root; + } writeFileSync( join(root, "metaobjects.config.ts"), ` @@ -175,6 +194,21 @@ describe("meta gen — imported nodes are excluded by default (FR-023)", () => { } }); + // agent/schema.md documents the project's own storage: the local Order, never an import. + test("(a2) agent/schema.md names no imported node", async () => { + const root = setupRepo({ agentDocs: true }); + try { + expect(await run(["gen", "--cwd", root])).toBe(0); + const schema = readFileSync(join(root, "docs", "agent", "schema.md"), "utf8"); + expect(schema).toContain("app::Order"); + for (const imported of ["Customer", "customers", "Address", "acme::common"]) { + expect(schema).not.toContain(imported); + } + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + test("(c) naming an excluded import positionally refuses with exit 2", async () => { const root = setupRepo(); try { diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts b/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts index db9c606d45..e5ad1c0e77 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-docs-file.ts @@ -100,8 +100,11 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G // With no expected schema (no dialect, so no `meta migrate` either), the model-only // page every port writes, read off the docs view. const content = schemaInput !== undefined - ? renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { provider }) - : renderAgentSchemaPageFromView(buildDocsView({ root: ctx.loadedRoot }), false, provider); + ? renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { + provider, + ...(ctx.select !== undefined && { inScope: ctx.select }), + }) + : renderAgentSchemaPageFromView(buildDocsView({ root: ctx.loadedRoot }), false, provider, ctx.select); if (content !== "") files.push({ path: `${dir}/schema.md`, content }); } diff --git a/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts b/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts index 2d4ef08eb6..74aa612863 100644 --- a/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts +++ b/server/typescript/packages/codegen-ts/src/generators/agent-schema-page.ts @@ -359,8 +359,14 @@ interface ModelFacts { readonly enums: readonly AgentSchemaEnumRow[]; } -function modelFacts(root: MetaRoot, schema: AgentSchemaInput, columnNamingStrategy: ColumnNamingStrategy): ModelFacts { - const objects = root.objects(); +function modelFacts( + root: MetaRoot, + schema: AgentSchemaInput, + columnNamingStrategy: ColumnNamingStrategy, + inScope: ((fqn: string) => boolean) | undefined, +): ModelFacts { + // A dependency's object the project did not take into scope is not the project's schema. + const objects = root.objects().filter((o) => inScope === undefined || inScope(o.resolutionKey())); // The qualified names the snapshot actually holds. An object whose physical name is not // one of these contributes nothing to the physical schema (an abstract base, a sourceless // value, an `@unmanaged` object) and must not appear on a page describing it — @@ -471,6 +477,9 @@ export interface AgentSchemaPageOptions { readonly physical?: boolean; /** Where the template is resolved. Default: the package's own templates. */ readonly provider?: Provider; + /** Keeps only the project's own objects (the run's `ctx.select`); a table or view a + * dependency's object declares is left out. Default: every object. */ + readonly inScope?: (fqn: string) => boolean; } /** @@ -481,11 +490,18 @@ export function agentSchemaPageData( root: MetaRoot, input: AgentSchemaInput, columnNamingStrategy: ColumnNamingStrategy, - opts?: { readonly physical?: boolean }, + opts?: { readonly physical?: boolean; readonly inScope?: (fqn: string) => boolean }, ): AgentSchemaPageData | undefined { - if (input.tables.length === 0 && input.views.length === 0) return undefined; + const inScope = opts?.inScope; + const own = (t: { name: string; schema?: string | undefined }): boolean => { + const fqn = input.provenance.get(input.qualify(t)); + return inScope === undefined || fqn === undefined || inScope(fqn); + }; + const ownTables = input.tables.filter(own); + const ownViews = input.views.filter(own); + if (ownTables.length === 0 && ownViews.length === 0) return undefined; const physical = opts?.physical !== false; - const facts = modelFacts(root, input, columnNamingStrategy); + const facts = modelFacts(root, input, columnNamingStrategy, inScope); // The semantics nudge. A schema page carrying business meaning beside the columns is // worth more to a reader working from it than any format choice this page could make — @@ -493,18 +509,18 @@ export function agentSchemaPageData( // snapshot already threads here to emit `COMMENT ON`. A model declaring none renders a // page of names with nothing to disambiguate them, and says so, because silently // omitting the highest-value content teaches an adopter that it does not exist. - const anyDescription = input.tables.some( + const anyDescription = ownTables.some( (t) => (t.description !== undefined && t.description !== "") || t.columns.some((c) => c.description !== undefined && c.description !== ""), ); - const tables = [...input.tables] + const tables = [...ownTables] .sort((a, b) => compareCodeUnits(a.name, b.name)) .map((table) => { const key = input.qualify(table); return tableOf(table, input, physical, input.provenance.get(key), facts.declaredBy.get(key) ?? new Map()); }); - const views = [...input.views] + const views = [...ownViews] .sort((a, b) => compareCodeUnits(a.name, b.name)) .map((view): AgentSchemaView => { const key = input.qualify(view); @@ -522,13 +538,13 @@ export function agentSchemaPageData( physical, dialect: physical ? input.dialect : "", hasMigrate: input.migrate, - descriptionNudge: !anyDescription && input.tables.length > 0, + descriptionNudge: !anyDescription && ownTables.length > 0, hasTables: tables.length > 0, tables, hasViews: views.length > 0, // A model with no report view must render exactly what it rendered before FR-044 // (no-churn: `meta verify --codegen` would flag drift after an upgrade otherwise). - hasReportView: input.views.some((v) => facts.reportViews.has(input.qualify(v))), + hasReportView: ownViews.some((v) => facts.reportViews.has(input.qualify(v))), views, hasRelationships: facts.relationships.length > 0, relationships: facts.relationships, diff --git a/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts b/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts index 4d8d7c1670..9fa89ea467 100644 --- a/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts +++ b/server/typescript/packages/codegen-ts/src/generators/docs-view-pages.ts @@ -238,9 +238,17 @@ function cardinalityPhrase(cardinality: unknown, through: string | undefined): s * The data `agent/schema.md.mustache` renders for the model-only page, built from the view * alone. `hasMigrate`: the project chose a `meta migrate` dialect (`migrate.dialect` in * `.metaobjects/config.json`). Undefined when the model declares no table and no view: no page. + * `inScope` keeps only the project's own objects (the run's `ctx.select`; undefined keeps every + * object): a dependency's object is not the project's schema. */ -export function agentSchemaPageDataFromView(view: DocsView, hasMigrate: boolean): AgentSchemaViewPageData | undefined { - const { tables, views } = view.storage; +export function agentSchemaPageDataFromView( + view: DocsView, + hasMigrate: boolean, + inScope?: (fqn: string) => boolean, +): AgentSchemaViewPageData | undefined { + const scoped = (id: string): boolean => inScope === undefined || inScope(id); + const tables = view.storage.tables.filter((t) => scoped(t.declaredBy.id)); + const views = view.storage.views.filter((v) => scoped(v.declaredBy.id)); if (tables.length === 0 && views.length === 0) return undefined; const members = membersById(view); const byOrder = [...view.nodes].sort((a, b) => a.order - b.order); @@ -290,7 +298,7 @@ export function agentSchemaPageDataFromView(view: DocsView, hasMigrate: boolean) // Every relationship as written, in declaration order of its object. const relationships: string[] = []; for (const n of byOrder) { - if (n.type !== TYPE_OBJECT) continue; + if (n.type !== TYPE_OBJECT || !scoped(n.id)) continue; for (const rel of directMembers(n, TYPE_RELATIONSHIP)) { const through = attrText(rel.attrs, "through"); const onDelete = attrText(rel.attrs, "onDelete"); @@ -342,8 +350,13 @@ export function agentSchemaPageDataFromView(view: DocsView, hasMigrate: boolean) /** The model-only `agent/schema.md`, rendered from the view; "" when the model declares no * table and no view. The page ends with exactly one line break. */ -export function renderAgentSchemaPageFromView(view: DocsView, hasMigrate: boolean, provider?: Provider): string { - const data = agentSchemaPageDataFromView(view, hasMigrate); +export function renderAgentSchemaPageFromView( + view: DocsView, + hasMigrate: boolean, + provider?: Provider, + inScope?: (fqn: string) => boolean, +): string { + const data = agentSchemaPageDataFromView(view, hasMigrate, inScope); if (data === undefined) return ""; const page = renderDocPage("agent/schema.md", data, provider ?? frameworkTemplatesProvider, "agent/schema.md"); // Keep one of the page's own trailing breaks (the template ends with one). diff --git a/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts b/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts index 09d2fe67af..cd39b6c897 100644 --- a/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts +++ b/server/typescript/packages/codegen-ts/src/reference/agent-docs.ts @@ -111,8 +111,11 @@ export const agentDocsFile = function agentDocsFile(opts?: AgentDocsFileOpts): G // With no expected schema (no dialect, so no `meta migrate` either), the model-only // page every port writes, read off the docs view. const content = schemaInput !== undefined - ? renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { provider }) - : renderAgentSchemaPageFromView(buildDocsView({ root: ctx.loadedRoot }), false, provider); + ? renderAgentSchemaPage(ctx.loadedRoot, schemaInput, columnNamingStrategy, { + provider, + ...(ctx.select !== undefined && { inScope: ctx.select }), + }) + : renderAgentSchemaPageFromView(buildDocsView({ root: ctx.loadedRoot }), false, provider, ctx.select); if (content !== "") files.push({ path: `${dir}/schema.md`, content }); } diff --git a/server/typescript/packages/codegen-ts/test/run-gen.test.ts b/server/typescript/packages/codegen-ts/test/run-gen.test.ts index dfe1915cfb..74e33d39b8 100644 --- a/server/typescript/packages/codegen-ts/test/run-gen.test.ts +++ b/server/typescript/packages/codegen-ts/test/run-gen.test.ts @@ -20,6 +20,7 @@ import { barrel } from "../src/generators/barrel.js"; import { entityFile } from "../src/generators/entity-file.js"; import { queriesFile } from "../src/generators/queries-file.js"; import { routesFile } from "../src/generators/routes-file.js"; +import { agentDocsFile } from "../src/generators/agent-docs-file.js"; import { MetaDataLoader } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; @@ -384,6 +385,33 @@ describe("runGen — scope", () => { expect(barrelContent).not.toContain("User"); }); + test("the model-only agent/schema.md documents the in-scope objects only", async () => { + const loader = new MetaDataLoader(); + const result = await loader.load([new FileSource(join(FIXTURE_DIR, "two-entities-fk.json"))]); + expect(result.errors).toEqual([]); + + // No `agentSchema` is handed to the run, so the page is the model-only one read off the + // docs view. An object outside the run's scope (a dependency's, in `meta gen`) is not the + // project's schema: its table and its heading stay off the page. + await runGen({ + config: defineConfig({ + outDir: tmp, + extStyle: "none", + dbImport: "~/server/db", + outputLayout: "flat" as const, dialect: "postgres", + targets: { docs: { outDir: join(tmp, "docs") } }, + generators: [agentDocsFile()], + }), + metadata: result.root, + scope: (fqn) => fqn === "demo::Post", + }); + + const schema = readFileSync(join(tmp, "docs", "agent", "schema.md"), "utf-8"); + expect(schema).toContain("Declared by `demo::Post`"); + expect(schema).not.toContain("Declared by `demo::User`"); + expect(schema).not.toContain("### `users`"); + }); + test("no scope option produces byte-identical output to an always-matching scope predicate", async () => { const loader = new MetaDataLoader(); const result = await loader.load([new FileSource(join(FIXTURE_DIR, "two-entities-fk.json"))]); From cce1e91b8cff6247332da044270cb983a68156b3 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 09:36:42 -0500 Subject: [PATCH 20/21] no-mistakes(test): apply changes made during test validation --- server/rust/metaobjects-codegen/tests/reference_nodes.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/server/rust/metaobjects-codegen/tests/reference_nodes.rs b/server/rust/metaobjects-codegen/tests/reference_nodes.rs index abd4f765b6..88fc44ab51 100644 --- a/server/rust/metaobjects-codegen/tests/reference_nodes.rs +++ b/server/rust/metaobjects-codegen/tests/reference_nodes.rs @@ -103,7 +103,10 @@ fn the_agent_schema_page_leaves_a_reference_node_out() { .iter() .find(|f| f.path == "agent/schema.md") .expect("agent-docs writes the schema page"); - assert!(schema.content.contains("acme::Ticket"), "the project's own table is listed"); + assert!( + schema.content.contains("acme::Ticket"), + "the project's own table is listed" + ); assert!( !schema.content.contains("Archive") && !schema.content.contains("archives"), "the reference node's table is not listed:\n{}", From 30d7c330eb34c0e25412b25ea57a4878766fe72a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 09:37:55 -0500 Subject: [PATCH 21/21] no-mistakes(document): Document schema page leaving out imported nodes --- docs/ports/rust.md | 3 ++- fixtures/docs-page-conformance/README.md | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/ports/rust.md b/docs/ports/rust.md index 4157deb91b..933bde7ade 100644 --- a/docs/ports/rust.md +++ b/docs/ports/rust.md @@ -492,7 +492,8 @@ role) is written to the table and read back through the view, so the fields that `requirements` writes the requirement ledger as `requirements.toon`, for tools; `agent-docs` writes `agent/requirements.md` (the node index and the embedded ledger) and the model-only `agent/schema.md` (tables, views, relationships and enums, without the SQL types, defaults, indexes and checks only the -TypeScript migration engine knows). Both read the docs view alone and render the shared +TypeScript migration engine knows; a reference node's table, view and relationships are left out, +as another run's to generate). Both read the docs view alone and render the shared `templates/requirements/` and `templates/agent/` Mustache pages, so the bytes are every port's (`fixtures/docs-page-conformance/`, run by `tests/docs_page_conformance.rs`). A same-path file under the project's `templates/` wins. No `requirement.*` node, no requirement page; no table and no view, diff --git a/fixtures/docs-page-conformance/README.md b/fixtures/docs-page-conformance/README.md index 7ff6d2c247..920417a69b 100644 --- a/fixtures/docs-page-conformance/README.md +++ b/fixtures/docs-page-conformance/README.md @@ -87,6 +87,11 @@ It leaves out the dialect facts: the SQL type and default columns, indexes (and them), foreign-key constraint names and referential actions. Only the TypeScript page, written from the expected schema, carries those; `agent/ui.md` stays a TypeScript page. +It also leaves out what is not the project's own storage: a dependency's object that +`scope.include` does not name (in Rust, which loads no dependency, a reference node) gives the +page no table, view, relationship or enum, in the physical TypeScript page too. These cases load +no dependency; each port's dependency-import test holds that rule. + One project setting reaches the page: `hasMigrate` is true when the project's `.metaobjects/config.json` sets `migrate.dialect` (it chose `meta migrate`, the reference migration helper). The page then says to change the schema with `meta migrate`; otherwise with