From 2bdc2289124ef0bfc8cb73a6ac77fd6ca28523e0 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 27 Nov 2026 19:43:15 -0500 Subject: [PATCH 01/13] feat(codegen): record each generated file's source node in C#, Java and Python manifests After a write run, the hash manifest entry of a per-object file now names its generator and the node's resolution key ({hash, generatedBy, sourceNode}, after the JVM's generator/outputDir), as TypeScript already did, so a docs view built from any of these ports lists each node's generated files. A whole-model file keeps the plain hash. A shared 'provenance' vector in fixtures/codegen-skip-conformance/manifests.json holds TypeScript, C#, Java and Python to the same entries. --- .../generated-file-provenance-all-ports.md | 10 ++ docs/features/explorer-data.md | 21 +-- docs/features/explorer-site.md | 2 +- docs/features/own-your-codegen.md | 5 +- fixtures/codegen-skip-conformance/README.md | 7 + .../codegen-skip-conformance/manifests.json | 108 +++++++++++++++- .../HashManifestPerPackageTests.cs | 104 +++++++++++++++ .../MetaObjects.Codegen/CodegenRunner.cs | 12 +- .../csharp/MetaObjects.Codegen/Generator.cs | 13 +- .../Generators/EntityGenerator.cs | 8 +- .../Generators/ExtractDelegateEmitter.cs | 2 +- .../Generators/ExtractorGenerator.cs | 2 +- .../Generators/OutputParserGenerator.cs | 2 +- .../Generators/OutputPromptGenerator.cs | 2 +- .../Generators/RenderHelperGenerator.cs | 2 +- .../Generators/ReportExportGenerator.cs | 2 +- .../Generators/ReverseFinders.cs | 2 +- .../Generators/RulesNamesGenerator.cs | 4 +- .../Generators/TemplateGenerator.cs | 4 +- .../MetaObjects.Codegen/HashManifest.cs | 48 +++++++ .../TemplateCodegen/ScopeWalk.cs | 3 +- .../direct/MultiFileDirectGeneratorBase.java | 2 +- .../javacode/ExtractorCodeGenerator.java | 2 +- .../generator/util/GeneratedFileWriter.java | 68 +++++++++- .../generator/util/HashManifest.java | 64 ++++++++- .../util/HashManifestPackagesTest.java | 36 ++++++ .../spring/SpringControllerGenerator.java | 12 +- .../generator/spring/SpringDtoGenerator.java | 2 +- .../SpringFilterAllowlistGenerator.java | 2 +- .../spring/SpringNamesGenerator.java | 2 +- .../spring/SpringOutputParserGenerator.java | 2 +- .../spring/SpringOutputPromptGenerator.java | 2 +- .../spring/SpringRenderHelperGenerator.java | 2 +- .../spring/SpringReportExportGenerator.java | 8 +- .../spring/SpringRepositoryGenerator.java | 6 +- .../spring/SpringValueObjectGenerator.java | 2 +- .../mojo/MetaDataGeneratorMojo.java | 4 +- .../com/metaobjects/mojo/RequiresCheck.java | 7 + .../mojo/GeneratedProvenanceTest.java | 122 ++++++++++++++++++ .../src/metaobjects/codegen/generator.py | 16 ++- .../codegen/generators/extractor_generator.py | 1 + .../codegen/generators/names_generator.py | 1 + .../generators/output_parser_generator.py | 1 + .../generators/output_prompt_generator.py | 1 + .../generators/render_helper_generator.py | 1 + .../generators/report_export_generator.py | 1 + .../codegen/generators/template_generator.py | 7 +- .../generators/trace_helper_generator.py | 1 + .../metaobjects/codegen/overwrite_policy.py | 78 ++++++++++- .../python/src/metaobjects/codegen/runner.py | 12 +- .../tests/codegen/test_gen_unchanged.py | 8 +- .../tests/codegen/test_manifest_store.py | 79 ++++++++++++ .../test/hash-manifest-store.test.ts | 40 +++++- ...-0064-skip-codegen-when-nothing-changed.md | 4 +- 54 files changed, 889 insertions(+), 70 deletions(-) create mode 100644 changelog.d/generated-file-provenance-all-ports.md create mode 100644 server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java diff --git a/changelog.d/generated-file-provenance-all-ports.md b/changelog.d/generated-file-provenance-all-ports.md new file mode 100644 index 0000000000..7045ab47ca --- /dev/null +++ b/changelog.d/generated-file-provenance-all-ports.md @@ -0,0 +1,10 @@ +- **C#, Java and Python codegen record which node each generated file came from.** After a write + run, the hash manifest entry of a per-object file names its generator and the node's resolution + key, `{ "hash", "generatedBy", "sourceNode" }` (after the JVM's `generator` and `outputDir`), + exactly as TypeScript already wrote it. A docs view built from any of these ports' manifests now + lists each node's generated files, so the explorer's "generated files" panel is filled. A file + rendered from the whole model or a package keeps the plain hash. The shared `provenance` vector in + `fixtures/codegen-skip-conformance/manifests.json` holds all four ports to the same entries. + + Upgrading: the next `gen` rewrites the committed `.metaobjects/.gen-state/.hashes/` files once, + adding the two fields to each per-object entry. Commit them; generated source files do not change. diff --git a/docs/features/explorer-data.md b/docs/features/explorer-data.md index 3670be7a73..79055782f5 100644 --- a/docs/features/explorer-data.md +++ b/docs/features/explorer-data.md @@ -94,10 +94,12 @@ comes from the `node` field. The structured payload is TypeScript-only, as the r ### Node provenance in the manifest -Each generated file now records the metadata node it was rendered from. A generator built with -`perEntity` sets this automatically. An `EmittedFile` can also name its node directly with -`sourceNode`, which is a node resolution key such as `acme::shop::Order`. `meta gen` then -writes that file's manifest entry in object form: +Each generated file now records the metadata node it was rendered from, in TypeScript, C#, +Java and Python. A per-object generator sets this automatically (TypeScript `perEntity`, C# +`PerEntityGenerator`, Python `per_entity`, and the shared writer the Java generators use). A +generated file can also name its node directly (`sourceNode` on a TypeScript `EmittedFile`, +`SourceNode` in C#, `source_node` in Python), as a node resolution key such as +`acme::shop::Order`. A write run then writes that file's manifest entry in object form: ```json { @@ -116,8 +118,11 @@ 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. TypeScript does not make that claim. TypeScript is the only port that writes -provenance today, and the JVM rewrites its manifest without these fields. +on that ownership, so a JVM entry carries both: `{ "hash", "generator", "outputDir", +"generatedBy", "sourceNode" }`. Every port writes 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. ## Building it by hand @@ -151,8 +156,8 @@ 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 JVM, Python and C# generators.** Their manifests have no `sourceNode` - yet, so for those ports a node lists no files. +- **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 the other ports.** TypeScript builds it today; the corpus is what the other ports will be held to. diff --git a/docs/features/explorer-site.md b/docs/features/explorer-site.md index 9bf9aa9556..5ba44abfef 100644 --- a/docs/features/explorer-site.md +++ b/docs/features/explorer-site.md @@ -167,7 +167,7 @@ dangling link. `buildDocsView` also takes the verify payload, the manifest and t the running application, and publishing the site. - "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 JVM, Python and C# generators (see +- 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. ## Verified by diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index b10aee9b41..c5ccdc05b7 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -534,8 +534,9 @@ overwritten; an edited one is refused by name (`keep`, th replaced (`overwrite`). There is **no three-way merge** (TypeScript-only). **Commit the manifest.** -A TypeScript entry can also carry the node the file was rendered from, -`{ "hash", "generatedBy", "sourceNode" }`. That is provenance, not ownership, which is why it +An entry can also carry the node the file was rendered from, +`{ "hash", "generatedBy", "sourceNode" }`; the TypeScript, C#, Java and Python runs write it +(on the JVM after `generator` and `outputDir`). That is provenance, not ownership, which is why it does not use the JVM's `generator` field. Every reader takes `hash` from either form. See [explorer-data.md](explorer-data.md#node-provenance-in-the-manifest). diff --git a/fixtures/codegen-skip-conformance/README.md b/fixtures/codegen-skip-conformance/README.md index a803f37568..40bec46c92 100644 --- a/fixtures/codegen-skip-conformance/README.md +++ b/fixtures/codegen-skip-conformance/README.md @@ -38,6 +38,13 @@ vectors in `manifests.json` are run by each port's manifest unit tests, beside t is one file's bytes in full), the legacy file is removed, and a second identical write changes no file. `gitignoreBefore` becomes `gitignoreAfter`; a file that already holds the new line, or has no `.gen-state/*` rule, is left alone. +- `provenance`: which generator, and which node, each recorded path came from (the docs view's + generated files). Seed `beforeFiles` as the `.hashes/` directory, record `records` with `objects` + 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. 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/codegen-skip-conformance/manifests.json b/fixtures/codegen-skip-conformance/manifests.json index ed5b57ff50..cb3fab4d1c 100644 --- a/fixtures/codegen-skip-conformance/manifests.json +++ b/fixtures/codegen-skip-conformance/manifests.json @@ -1,5 +1,5 @@ { - "$comment": "ADR-0064 Amendment 1. Every port with hash state runs these vectors against its own manifest store: fileNames (a package's manifest file name), placement (which manifest a path is filed under, given the loaded objects) and legacySplit (a legacy .hashes.json becomes these package files, byte for byte, and is removed). 'package': null is the root manifest (.root.json). A manifest file's text is the object with keys sorted, two-space indentation and a trailing newline ('goldenText' is one file in full).", + "$comment": "ADR-0064 Amendment 1. Every port with hash state runs these vectors against its own manifest store: fileNames (a package's manifest file name), placement (which manifest a path is filed under, given the loaded objects), legacySplit (a legacy .hashes.json becomes these package files, byte for byte, and is removed) and provenance (which generator and node each recorded path came from). 'package': null is the root manifest (.root.json). A manifest file's text is the object with keys sorted, two-space indentation and a trailing newline ('goldenText' is one file in full).", "version": 1, "objects": [ { @@ -277,5 +277,111 @@ "goldenText": "{\n \"gen/Order.ts\": \"h1\",\n \"gen/OrderDto.java\": {\n \"hash\": \"h2\",\n \"generator\": \"java:dto\",\n \"outputDir\": \"gen\"\n }\n}\n", "gitignoreBefore": ".gen-state/*\n!.gen-state/.hashes.json\n", "gitignoreAfter": ".gen-state/*\n!.gen-state/.hashes/\n" + }, + "provenance": { + "$comment": "Generated-file provenance (the docs view's 'files'): after a write run, each recorded path's entry names the generator that wrote it and, for a file rendered from one node, that node's resolution key. A port seeds 'beforeFiles' as its .hashes/ directory, records 'records' (with the vectors' 'objects' as the loaded model), and must then hold exactly 'afterFiles'. A record with a sourceNode makes the entry { hash, , generatedBy, sourceNode }; one without returns the entry to the plain hash (or to { hash, } when it has owner fields); a path with no recorded hash is left out; the sourceNode then places the entry. 'goldenText' is one file's bytes in full. Recording the same records a second time changes no file.", + "beforeFiles": { + "acme.shop.json": { + "gen/Order.ts": "h1", + "gen/OrderDto.java": { + "hash": "h2", + "generator": "java:dto", + "outputDir": "gen" + } + }, + "acme.crm.json": { + "gen/Customer.ts": { + "hash": "h3", + "generatedBy": "entity", + "sourceNode": "acme::crm::Customer" + } + }, + "acme.billing.json": { + "gen/Invoice.ts": "h5" + }, + "gone.json": { + "gen/index.ts": { + "hash": "h4", + "generatedBy": "barrel", + "sourceNode": "gone::X" + } + }, + ".root.json": { + "gen/Item.ts": "h6" + } + }, + "records": [ + { + "path": "gen/Order.ts", + "generatedBy": "entity", + "sourceNode": "acme::shop::Order", + "why": "a per-object file gains its generator and node" + }, + { + "path": "gen/OrderDto.java", + "generatedBy": "dto", + "sourceNode": "acme::shop::Order", + "why": "the JVM owner fields stay, before the provenance" + }, + { + "path": "gen/index.ts", + "generatedBy": "barrel", + "why": "a whole-model file returns to the plain hash and is placed by its stem" + }, + { + "path": "gen/Customer.ts", + "generatedBy": "entity", + "sourceNode": "acme::crm::Customer", + "why": "already recorded so: unchanged" + }, + { + "path": "gen/Item.ts", + "generatedBy": "entity", + "sourceNode": "acme::crm::Item", + "why": "the sourceNode places a file the stem cannot" + }, + { + "path": "gen/Missing.ts", + "generatedBy": "entity", + "sourceNode": "acme::shop::Missing", + "why": "no recorded hash: provenance never records a write" + } + ], + "afterFiles": { + "acme.shop.json": { + "gen/Order.ts": { + "hash": "h1", + "generatedBy": "entity", + "sourceNode": "acme::shop::Order" + }, + "gen/OrderDto.java": { + "hash": "h2", + "generator": "java:dto", + "outputDir": "gen", + "generatedBy": "dto", + "sourceNode": "acme::shop::Order" + } + }, + "acme.crm.json": { + "gen/Customer.ts": { + "hash": "h3", + "generatedBy": "entity", + "sourceNode": "acme::crm::Customer" + }, + "gen/Item.ts": { + "hash": "h6", + "generatedBy": "entity", + "sourceNode": "acme::crm::Item" + } + }, + "acme.billing.json": { + "gen/Invoice.ts": "h5" + }, + ".root.json": { + "gen/index.ts": "h4" + } + }, + "goldenFile": "acme.shop.json", + "goldenText": "{\n \"gen/Order.ts\": {\n \"hash\": \"h1\",\n \"generatedBy\": \"entity\",\n \"sourceNode\": \"acme::shop::Order\"\n },\n \"gen/OrderDto.java\": {\n \"hash\": \"h2\",\n \"generator\": \"java:dto\",\n \"outputDir\": \"gen\",\n \"generatedBy\": \"dto\",\n \"sourceNode\": \"acme::shop::Order\"\n }\n}\n" } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs index df0fa80adf..78704a12a7 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs @@ -107,6 +107,110 @@ public void LegacySplit_matches_the_vectors() Assert.Equal(split.GetProperty("gitignoreAfter").GetString(), File.ReadAllText(ignore)); } + [Fact] + public void Provenance_matches_the_vectors() + { + var v = Vectors(); + var p = v.GetProperty("provenance"); + var objects = VectorObjects(v); + Directory.CreateDirectory(HashesDir); + foreach (var f in p.GetProperty("beforeFiles").EnumerateObject()) + File.WriteAllText(Path.Combine(HashesDir, f.Name), f.Value.GetRawText()); + var records = p.GetProperty("records").EnumerateArray().ToDictionary( + r => r.GetProperty("path").GetString()!, + r => new HashManifest.Provenance(r.GetProperty("generatedBy").GetString()!, Str(r, "sourceNode"))); + + void Apply() + { + using var batch = HashManifest.Batch(StateDir, objects); + HashManifest.RecordGeneratedProvenance(StateDir, records); + batch.Complete(); + } + Apply(); + + var expected = p.GetProperty("afterFiles"); + Assert.Equal(expected.EnumerateObject().Select(f => f.Name).Order(StringComparer.Ordinal).ToList(), + Directory.GetFiles(HashesDir).Select(Path.GetFileName).Order(StringComparer.Ordinal).ToList()); + foreach (var f in expected.EnumerateObject()) + { + using var actual = JsonDocument.Parse(File.ReadAllText(Path.Combine(HashesDir, f.Name))); + Assert.Equal(Canon(f.Value), Canon(actual.RootElement)); + } + Assert.Equal(p.GetProperty("goldenText").GetString()!, + File.ReadAllText(Path.Combine(HashesDir, p.GetProperty("goldenFile").GetString()!))); + + var stamp = DateTime.UtcNow.AddHours(-2); + foreach (var f in Directory.GetFiles(HashesDir)) File.SetLastWriteTimeUtc(f, stamp); + Apply(); + foreach (var f in Directory.GetFiles(HashesDir)) Assert.Equal(stamp, File.GetLastWriteTimeUtc(f)); + } + + private static string Canon(JsonElement e) => JsonSerializer.Serialize(e); + + [Fact] + public void The_real_entity_generator_stamps_its_entity_file_with_provenance() + { + var src = """ + { "metadata.root": { "package": "acme::shop", "children": [ + { "object.entity": { "name": "Order", "children": [ + { "field.string": { "name": "id" } } ] } } + ]}} + """; + var r = new MetaDataLoader().Load([new InMemoryStringSource(src, id: "shop.json")]); + Assert.Empty(r.Errors); + var config = new GenConfig + { + OutDir = Path.Combine(_root, "gen"), Namespace = "Probe", GenStateDir = StateDir, ProjectRoot = _root, + }; + CodegenRunner.Run(config, r.Root, [new MetaObjects.Codegen.Generators.EntityGenerator()]); + + using var shop = JsonDocument.Parse(File.ReadAllText(Path.Combine(HashesDir, "acme.shop.json"))); + var entry = shop.RootElement.EnumerateObject().Single(p => p.Name.EndsWith("Order.g.cs")).Value; + Assert.Equal(JsonValueKind.Object, entry.ValueKind); + Assert.Equal("entity-generator", entry.GetProperty("generatedBy").GetString()); + Assert.Equal("acme::shop::Order", entry.GetProperty("sourceNode").GetString()); + Assert.True(entry.TryGetProperty("hash", out _)); + } + + private sealed class WholeModelFile : IGenerator + { + public string Name => "barrel"; + public IEnumerable Generate(GenContext ctx) => [new EmittedFile("index.g.cs", "// index\n")]; + } + + private sealed class OneEntity : PerEntityGenerator + { + public override string Name => "alpha"; + protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) => + new($"{entity.Name}.alpha.cs", "// a\n"); + } + + [Fact] + public void A_run_records_the_generator_and_node_for_a_per_entity_file_only() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(Pkg("acme::shop", "Order"), id: "shop.json")]); + Assert.Empty(r.Errors); + var config = new GenConfig + { + OutDir = Path.Combine(_root, "gen"), Namespace = "Probe", GenStateDir = StateDir, ProjectRoot = _root, + }; + CodegenRunner.Run(config, r.Root, [new OneEntity(), new WholeModelFile()]); + + using var shop = JsonDocument.Parse(File.ReadAllText(Path.Combine(HashesDir, "acme.shop.json"))); + var entry = shop.RootElement.GetProperty("gen/Order.alpha.cs"); + Assert.Equal(["hash", "generatedBy", "sourceNode"], entry.EnumerateObject().Select(x => x.Name).ToArray()); + Assert.Equal("alpha", entry.GetProperty("generatedBy").GetString()); + Assert.Equal("acme::shop::Order", entry.GetProperty("sourceNode").GetString()); + using var rootM = JsonDocument.Parse(File.ReadAllText(Path.Combine(HashesDir, ".root.json"))); + Assert.Equal(JsonValueKind.String, rootM.RootElement.GetProperty("gen/index.g.cs").ValueKind); + + // A second run changes no manifest file. + var stamp = DateTime.UtcNow.AddHours(-2); + foreach (var f in Directory.GetFiles(HashesDir)) File.SetLastWriteTimeUtc(f, stamp); + CodegenRunner.Run(config, r.Root, [new OneEntity(), new WholeModelFile()]); + foreach (var f in Directory.GetFiles(HashesDir)) Assert.Equal(stamp, File.GetLastWriteTimeUtc(f)); + } + private static readonly List Objs = [ new("Order", "acme::shop"), new("Customer", "acme::crm"), diff --git a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs index cec13e66be..ef62b5c25b 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs @@ -116,6 +116,8 @@ internal static RunResult Run( ? names.ToHashSet(StringComparer.Ordinal) : null; // ADR-0064 — loaded once, saved once and only when it changed (see HashManifest.Session). var manifest = config.GenStateDir is { } stateDir ? new HashManifest.Session(stateDir) : null; + // Which generator wrote each recorded path, and from which node (HashManifest.RecordGeneratedProvenance). + var provenance = new Dictionary(StringComparer.Ordinal); // Saved even when a generator throws, so the manifest keeps matching the files already written. try @@ -177,13 +179,21 @@ internal static RunResult Run( $"overwrote hand-edited {reported} with fresh output (handEdits: Overwrite on {generator.Name})"); status = "written"; } + if (!outside && manifest is not null) + provenance[key] = new HashManifest.Provenance(generator.Name, file.SourceNode); results.Add(new WriteResult(reported, status)); if (status == "refused") refused.Add(reported); else if (status == "adopted") adopted.Add(reported); } } } - finally { manifest?.Save(); } + finally + { + manifest?.Save(); + // After the hashes are saved: provenance describes a recorded write, it never records one. + if (config.GenStateDir is { } provDir && config.ProjectRoot is not null && provenance.Count > 0) + HashManifest.RecordGeneratedProvenance(provDir, provenance); + } // 1.3.0 moved the helper runtime into its own package; say so when the app would not compile. warnings.AddRange(HelperRuntimeReference.WarningsForImporting(helperImports)); diff --git a/server/csharp/MetaObjects.Codegen/Generator.cs b/server/csharp/MetaObjects.Codegen/Generator.cs index 6fcd864560..b41c6c0191 100644 --- a/server/csharp/MetaObjects.Codegen/Generator.cs +++ b/server/csharp/MetaObjects.Codegen/Generator.cs @@ -16,6 +16,13 @@ public sealed record EmittedFile(string Path, string Content) /// it. false, the default, is a per-object file the selection narrows. /// public bool WholeModel { get; init; } + + /// + /// The resolution key (acme::shop::Order) of the one metadata node this file was rendered + /// from; null for a file built from the whole model or a package. Recorded in the hash + /// manifest as provenance. stamps it unless the generator set one. + /// + public string? SourceNode { get; init; } } /// Resolved generation config. @@ -713,7 +720,11 @@ public abstract class PerEntityGenerator : IGenerator protected abstract EmittedFile GenerateOne(MetaObject entity, GenContext ctx); public virtual IEnumerable Generate(GenContext ctx) => - ctx.Narrow(Include).Entities.Where(Filter).Select(e => GenerateOne(e, ctx)); + ctx.Narrow(Include).Entities.Where(Filter).Select(e => + { + var file = GenerateOne(e, ctx); + return file.SourceNode is null ? file with { SourceNode = e.ResolutionKey() } : file; + }); /// /// Scope this entry to some objects: only those it accepts are generated for. Set on the diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index ee4aee8a86..6cd1b6d56f 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -447,7 +447,7 @@ private EmittedFile EmitMappedClassImpl( } EmitClassBodyTrailer(w, entity, ctx); } - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), w.ToString()) { SourceNode = entity.ResolutionKey() }; } // Extension hook — owns the per-class header for a mapped entity/projection: the @@ -720,7 +720,7 @@ protected virtual EmittedFile EmitTphSubtypeClass(MetaObject entity, GenContext } EmitClassBodyTrailer(w, entity, ctx); } - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), w.ToString()) { SourceNode = entity.ResolutionKey() }; } // A subtype-only scalar property: [Column]-mapped, with the field's validator @@ -921,7 +921,7 @@ protected virtual EmittedFile EmitAbstractShapeClass(MetaObject entity, GenConte } EmitClassBodyTrailer(w, entity, ctx); } - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{className}.g.cs"), w.ToString()) { SourceNode = entity.ResolutionKey() }; } // Plain POCO for a value object nested by an owned-type navigation. No [Table] / @@ -1002,7 +1002,7 @@ protected virtual EmittedFile EmitAbstractShapeClass(MetaObject entity, GenConte } EmitClassBodyTrailer(w, vo, ctx); } - return new EmittedFile(OutputPaths.Of(vo, ctx, $"{className}.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(vo, ctx, $"{className}.g.cs"), w.ToString()) { SourceNode = vo.ResolutionKey() }; } /// diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExtractDelegateEmitter.cs b/server/csharp/MetaObjects.Codegen/Generators/ExtractDelegateEmitter.cs index cf42eeeebb..79bf04ac67 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ExtractDelegateEmitter.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ExtractDelegateEmitter.cs @@ -168,7 +168,7 @@ public static EmittedFile MirrorFile(MetaData vo, MetaData root, GenConfig confi foreach (var f in Fr010FieldMapping.Fields(vo)) w.Line($"public {NestedMirrorType(f, root, config, ns)} {f.Name} {{ get; init; }}"); } - return new EmittedFile(OutputPaths.Of(vo, config, $"{name}.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(vo, config, $"{name}.g.cs"), w.ToString()) { SourceNode = vo.ResolutionKey() }; } // ========================================================================= diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs index be4640ec41..b3b5cc14bf 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs @@ -98,7 +98,7 @@ protected virtual EmittedFile EmitExtractor(MetaData tmpl, MetaData vo, string p WriteMapper(w, v, ctx); } - return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{extractorClass}.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{extractorClass}.cs"), w.ToString()) { SourceNode = tmpl.ResolutionKey() }; } // The pieces of the file, one overridable method each (ADR-0063 item 7): a subclass changes the diff --git a/server/csharp/MetaObjects.Codegen/Generators/OutputParserGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/OutputParserGenerator.cs index 32ed579aca..43bb5f41bb 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/OutputParserGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/OutputParserGenerator.cs @@ -175,7 +175,7 @@ protected virtual EmittedFile EmitParser(MetaData tmpl, string responseRef, GenC // ADR-0052 D4: the artifact name follows the DIRECTION axis. A parser file named // `.output.cs` generated from a prompt reproduces the confusion being removed. - return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.response.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.response.cs"), w.ToString()) { SourceNode = tmpl.ResolutionKey() }; } // The pieces of the file, one overridable method each (ADR-0063 item 7): a subclass changes the diff --git a/server/csharp/MetaObjects.Codegen/Generators/OutputPromptGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/OutputPromptGenerator.cs index 8ab38ab874..0574dd3cff 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/OutputPromptGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/OutputPromptGenerator.cs @@ -73,7 +73,7 @@ protected virtual EmittedFile EmitPrompt(MetaData tmpl, MetaData vo, string payl } // ADR-0052 D4: the artifact name follows the DIRECTION axis. A file named // `.prompt.cs` generated from a prompt reproduces the confusion being removed. - return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.responseFormat.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.responseFormat.cs"), w.ToString()) { SourceNode = tmpl.ResolutionKey() }; } // The pieces of the file, one overridable method each (ADR-0063 item 7): a subclass changes the diff --git a/server/csharp/MetaObjects.Codegen/Generators/RenderHelperGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RenderHelperGenerator.cs index 261be9a126..67aacb9fe2 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RenderHelperGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RenderHelperGenerator.cs @@ -230,7 +230,7 @@ protected virtual EmittedFile EmitHelper(MetaData tmpl, MetaData vo, string payl w.Line($"global::MetaObjects.Render.Renderer.Render(new global::MetaObjects.Render.RenderRequest {{ Ref = {Quote(textRef)}, Payload = payload, Provider = provider, Format = {Quote(format)}, Verify = {ft}{maxCharsArg} }});"); } } - return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.render.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(tmpl, ctx, $"{templateName}.render.cs"), w.ToString()) { SourceNode = tmpl.ResolutionKey() }; } // ------------------------------------------------------------------------- diff --git a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs index cc3e32db60..5abe044311 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs @@ -83,7 +83,7 @@ public IEnumerable Generate(GenContext ctx) yield return new EmittedFile("ReportExportWriter.g.cs", SharedWriter(ctx, HasDurationColumn(served))) { WholeModel = true }; foreach (var report in served) - yield return new EmittedFile(OutputPaths.Of(report, ctx, CSharpNaming.Pascal(report.Name) + "Export.g.cs"), ReportModule(report, ctx)); + yield return new EmittedFile(OutputPaths.Of(report, ctx, CSharpNaming.Pascal(report.Name) + "Export.g.cs"), ReportModule(report, ctx)) { SourceNode = report.ResolutionKey() }; } protected static string Literal(bool b) => b ? "true" : "false"; diff --git a/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs b/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs index 29133997a2..91b1496c9c 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ReverseFinders.cs @@ -182,6 +182,6 @@ private static string FkValueType(MetaObject entity, ReverseFk fk, MetaRoot root } } } - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{queriesCls}.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{queriesCls}.g.cs"), w.ToString()) { SourceNode = entity.ResolutionKey() }; } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs index d48755269b..17ea41a47c 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RulesNamesGenerator.cs @@ -109,7 +109,7 @@ protected static IReadOnlyList Operations(MetaData api) => WriteLifecycle(w, entity, l, commands, lifecycleClasses.Add(Ident(l.Field.Name), $"field \"{l.Field.Name}\"")); } } - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}.g.cs"), w.ToString()) { SourceNode = entity.ResolutionKey() }; } /// One lifecycle field as a nested class. @@ -181,7 +181,7 @@ protected virtual void WriteLifecycle(CsWriter w, MetaObject entity, Lifecycle l WriteOperation(w, op, members.Add(Ident(op.Name), $"operation \"{op.Name}\"")); } } - return new EmittedFile(OutputPaths.Of(api, ctx, $"{cls}.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(api, ctx, $"{cls}.g.cs"), w.ToString()) { SourceNode = api.ResolutionKey() }; } /// One operation as a nested class. diff --git a/server/csharp/MetaObjects.Codegen/Generators/TemplateGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/TemplateGenerator.cs index 906479b4c8..82af7f6808 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/TemplateGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/TemplateGenerator.cs @@ -12,7 +12,7 @@ namespace MetaObjects.Codegen.Generators; -public record TemplateWalkResult(object Data, string OutputPath); +public record TemplateWalkResult(object Data, string OutputPath, string? SourceNode = null); public static class TemplateGenerator { @@ -59,7 +59,7 @@ public IEnumerable Generate(GenContext ctx) Format = _format, }; var content = Renderer.Render(request); - yield return new EmittedFile(entry.OutputPath, content); + yield return new EmittedFile(entry.OutputPath, content) { SourceNode = entry.SourceNode }; } } } diff --git a/server/csharp/MetaObjects.Codegen/HashManifest.cs b/server/csharp/MetaObjects.Codegen/HashManifest.cs index 7376494318..fd7de3a717 100644 --- a/server/csharp/MetaObjects.Codegen/HashManifest.cs +++ b/server/csharp/MetaObjects.Codegen/HashManifest.cs @@ -450,6 +450,54 @@ public static bool IsPristine( public static bool IsRecorded(string genStateDir, string relPath, string? legacyRelPath = null) => Recorded(genStateDir, relPath, legacyRelPath) is not null; + /// What produced one generated file: the generator, and the node it was rendered from (if one). + public readonly record struct Provenance(string GeneratedBy, string? SourceNode); + + private static readonly string[] ProvenanceFields = ["generatedBy", "sourceNode"]; + + /// + /// Record, on each recorded path's entry, the generator and node it came from. An entry with a + /// source node becomes { hash, ...other fields, generatedBy, sourceNode }; one without + /// returns to the plain hash (or { hash, ...other fields }). A path with no recorded hash is + /// left alone: this never records a write. Nothing is written when no entry changes. + /// + public static void RecordGeneratedProvenance(string genStateDir, IReadOnlyDictionary provenance) + { + if (!Exists(genStateDir)) return; + var batch = BatchFor(genStateDir); + var loaded = batch is null ? ReadAll(genStateDir) : null; + var raw = batch?.Raw ?? loaded!.Raw; + var changed = false; + foreach (var (key, prov) in provenance) + { + if (!raw.TryGetValue(key, out var existing) || EntryHash(existing) is not { } hash) continue; + var rest = new List>(); + if (existing.ValueKind == JsonValueKind.Object) + foreach (var prop in existing.EnumerateObject()) + if (prop.Name != "hash" && !ProvenanceFields.Contains(prop.Name)) + rest.Add(new(prop.Name, prop.Value)); + JsonElement next; + if (prov.SourceNode is null && rest.Count == 0) next = JsonSerializer.SerializeToElement(hash); + else + { + var entry = new Dictionary(StringComparer.Ordinal) { ["hash"] = hash }; + foreach (var (k, v) in rest) entry[k] = v; + if (prov.SourceNode is not null) + { + entry["generatedBy"] = prov.GeneratedBy; + entry["sourceNode"] = prov.SourceNode; + } + next = JsonSerializer.SerializeToElement(entry); + } + if (JsonSerializer.Serialize(next) == JsonSerializer.Serialize(existing)) continue; + raw[key] = next; + changed = true; + } + if (!changed) return; + if (batch is not null) batch.Dirty = true; + else WriteAll(genStateDir, raw, loaded!.Origin, null); + } + /// /// ADR-0064 — one run's view of the manifest: loaded ONCE, updated in memory, saved ONCE and /// only when an entry was added, changed or removed. A run that changes nothing leaves the diff --git a/server/csharp/MetaObjects.Codegen/TemplateCodegen/ScopeWalk.cs b/server/csharp/MetaObjects.Codegen/TemplateCodegen/ScopeWalk.cs index e2a7c270da..b094157725 100644 --- a/server/csharp/MetaObjects.Codegen/TemplateCodegen/ScopeWalk.cs +++ b/server/csharp/MetaObjects.Codegen/TemplateCodegen/ScopeWalk.cs @@ -34,7 +34,8 @@ public static Func> ForScope(string sc case PerEntity: return concrete.Select(o => new TemplateWalkResult( TemplateData.Entity(o), - OutputPattern.Expand(outputPattern, TemplateData.BareName(o), TemplateData.PackageOf(o)))) + OutputPattern.Expand(outputPattern, TemplateData.BareName(o), TemplateData.PackageOf(o)), + o.ResolutionKey())) .ToList(); case PerPackage: var byPkg = new SortedDictionary>(StringComparer.Ordinal); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java index 1cc1afeb9c..43055dd556 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java @@ -86,7 +86,7 @@ public void execute( MetaDataLoader loader ) { writer.close(); writer = null; - GeneratedFileWriter.write( f.toPath(), buffer.toString() ); + GeneratedFileWriter.write( f.toPath(), buffer.toString(), md ); pw = null; } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java index e707ea668b..ad67cbb6c9 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/ExtractorCodeGenerator.java @@ -154,7 +154,7 @@ public void emit(File outputDir, String javaPackage, String className, String re // Guarded like every other generator on this port: writeHeader emits the GENERATED // marker, so our own output is still overwritten freely while a hand-written extractor // at this path is refused. - GeneratedFileWriter.write(src.toPath(), w.toString()); + GeneratedFileWriter.write(src.toPath(), w.toString(), resolutionKey); } /** Write the package declaration and the class JavaDoc. */ diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java index 31683df3ee..7cdfa0fcb6 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java @@ -1,5 +1,6 @@ package com.metaobjects.generator.util; +import com.metaobjects.MetaData; import com.metaobjects.generator.GeneratorException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -143,6 +144,12 @@ public static final class Run implements AutoCloseable { private String current = "(unattributed generator)"; private String currentHandEdits = HAND_EDITS_KEEP; private HashManifest.Owner currentOwner; + // What the generator is called in the manifest's provenance, and what each recorded path was + // rendered from. The map starts as what the manifest already says, so an unchanged run is clean. + private String currentGeneratedBy = current; + private Map provenance; + // The node the write in progress was rendered from; null for a whole-model file. + private String currentSourceNode; // Manifest configuration — unset (null genStateDir/projectRoot) means "no manifest // for this run", which keeps every write on the legacy marker-only rule. Set once, @@ -194,9 +201,20 @@ public Run attributeTo(String generatorName) { * Called once per generator by the runner, before that generator executes. */ public Run attributeTo(String generatorName, String handEdits, HashManifest.Owner owner) { + return attributeTo(generatorName, handEdits, owner, generatorName); + } + + /** + * {@link #attributeTo(String, String, HashManifest.Owner)} that also names the generator as + * the manifest's {@code generatedBy} provenance field says it (its stable registry name, e.g. + * {@code dto}); the other overloads use {@code generatorName}. + */ + public Run attributeTo(String generatorName, String handEdits, HashManifest.Owner owner, + String generatedBy) { this.current = generatorName; this.currentHandEdits = handEdits; this.currentOwner = owner; + this.currentGeneratedBy = generatedBy; return this; } @@ -212,6 +230,7 @@ public Run configureManifest(Path genStateDir, Path projectRoot) { this.projectRoot = projectRoot; this.hashes = HashManifest.load(genStateDir); this.owners = HashManifest.loadOwners(genStateDir); + this.provenance = HashManifest.loadProvenance(genStateDir); // A run that finds the pre-1.3.0 single manifest always saves, so it is migrated. this.dirty = HashManifest.hasLegacy(genStateDir); return this; @@ -234,7 +253,7 @@ public Run placeBy(HashManifest.Placement placement) { * calls it for whatever is still unwritten. */ public void flush() { if (!dirty) return; - HashManifest.save(genStateDir, hashes, owners, placement); + HashManifest.save(genStateDir, hashes, owners, placement, provenance); dirty = false; } @@ -242,6 +261,16 @@ private void record(String key, String hash) { if (!hash.equals(hashes.put(key, hash))) dirty = true; HashManifest.Owner previous = currentOwner == null ? owners.remove(key) : owners.put(key, currentOwner); if (!Objects.equals(previous, currentOwner)) dirty = true; + // Provenance: the generator, and the node when this file was rendered from one. A file + // with no node, written by a generator the manifest names nothing for, stays plain. + HashManifest.Provenance now = new HashManifest.Provenance(currentGeneratedBy, currentSourceNode); + HashManifest.Provenance before = provenance.get(key); + if (currentSourceNode != null) { + if (!now.equals(provenance.put(key, now))) dirty = true; + } else if (before != null && before.sourceNode() != null) { + provenance.put(key, now); // returns the entry to the plain form + dirty = true; + } } /** The files written, left in place, or adopted this run — the orphan sweep's @@ -416,6 +445,43 @@ public static Outcome writeUnmarked(Path outFile, String content) throws IOExcep return write(outFile, content, true); } + /** + * {@link #write(Path, String)} for a file rendered from one metadata node: the manifest entry + * also names that node's resolution key ({@code pkg::Name}) as {@code sourceNode}, and the + * generator as {@code generatedBy}. A file rendered from the whole model (a barrel, a names + * index) uses the overload without a node and carries no {@code sourceNode}. + */ + public static Outcome write(Path outFile, String content, MetaData sourceNode) throws IOException { + return writeFrom(sourceNode == null ? null : resolutionKey(sourceNode), outFile, content, false); + } + + /** {@link #write(Path, String, MetaData)} for a caller that holds the node's resolution key, not the node. */ + public static Outcome write(Path outFile, String content, String sourceNodeKey) throws IOException { + return writeFrom(sourceNodeKey, outFile, content, false); + } + + /** {@link #writeUnmarked(Path, String)} for a file rendered from one metadata node. */ + public static Outcome writeUnmarked(Path outFile, String content, MetaData sourceNode) throws IOException { + return writeFrom(sourceNode == null ? null : resolutionKey(sourceNode), outFile, content, true); + } + + private static Outcome writeFrom(String sourceNodeKey, Path outFile, String content, boolean unmarked) + throws IOException { + Run run = ACTIVE_RUN.get(); + if (run == null || sourceNodeKey == null) return write(outFile, content, unmarked); + run.currentSourceNode = sourceNodeKey; + try { + return write(outFile, content, unmarked); + } finally { + run.currentSourceNode = null; + } + } + + /** The node's resolution key as every port writes it: {@code pkg::Name}, or the bare name with no package. */ + public static String resolutionKey(MetaData node) { + return node.getName(); + } + /** {@link #writeUnmarked(Path, String)} for UTF-8 bytes already encoded. */ public static Outcome writeUnmarked(Path outFile, byte[] utf8) throws IOException { return write(outFile, new String(utf8, StandardCharsets.UTF_8), true); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java index bcba020a0f..4fc6ac5b04 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java @@ -50,6 +50,10 @@ * {@code "": ""} form, the form the other ports write, reads as recorded with * no owner, and so does an entry carrying the execution-id {@code "owner"} field an * earlier 8.1.0 build wrote. + * + *

A file a write run rendered from one metadata node also carries {@code "generatedBy"} (the + * generator's stable name) and {@code "sourceNode"} (the node's resolution key, {@code pkg::Name}), + * after the owner fields; a whole-model file carries neither ({@link Provenance}). */ public final class HashManifest { @@ -64,6 +68,15 @@ public String toString() { } } + /** + * What produced one generated file: the generator, and the metadata node (its resolution key, + * {@code pkg::Name}) it was rendered from, or {@code null} for a file rendered from the whole + * model. Written as {@code generatedBy} and {@code sourceNode}, the fields every port shares; + * deliberately NOT the {@code generator} owner field, which is an ownership claim the orphan + * sweep acts on. + */ + public record Provenance(String generatedBy, String sourceNode) {} + /** The pre-1.3.0 single manifest, still read (underneath the package files) and removed by the next write. */ private static final String LEGACY_FILE_NAME = ".hashes.json"; /** The directory of per-package manifests (ADR-0064 Amendment 1). */ @@ -252,6 +265,18 @@ public static Map loadOwners(Path genStateDir) { return out; } + /** Load the provenance of every entry that names a generator; a plain entry is absent. */ + public static Map loadProvenance(Path genStateDir) { + Map out = new LinkedHashMap<>(); + for (Map.Entry e : entries(genStateDir).entrySet()) { + if (!e.getValue().isJsonObject()) continue; + JsonObject entry = e.getValue().getAsJsonObject(); + String generatedBy = stringField(entry, "generatedBy"); + if (generatedBy != null) out.put(e.getKey(), new Provenance(generatedBy, stringField(entry, "sourceNode"))); + } + return out; + } + /** The union of every manifest file: the legacy one underneath, package files in name order on top. */ private static Map entries(Path genStateDir) { Map out = new LinkedHashMap<>(); @@ -309,6 +334,18 @@ public static void save(Path genStateDir, Map hashes, Map hashes, Map owners, Placement placement) { + save(genStateDir, hashes, owners, placement, Map.of()); + } + + /** + * {@link #save(Path, Map, Map, Placement)} that also writes {@code provenance}. A key with a + * source node becomes {@code { "hash", , "generatedBy", + * "sourceNode" }}; a key whose provenance has none returns to the plain hash (or to + * {@code { "hash", }} when it has owner fields). A key absent from + * {@code provenance} keeps whatever it carried, and a provenance key with no hash records nothing. + */ + public static void save(Path genStateDir, Map hashes, Map owners, + Placement placement, Map provenance) { try { Map existing = entries(genStateDir); Map currentFile = placement == null ? fileOfKeys(genStateDir) : Map.of(); @@ -317,18 +354,21 @@ public static void save(Path genStateDir, Map hashes, Map f : prior.getAsJsonObject().entrySet()) { String name = f.getKey(); if (!name.equals("hash") && !name.equals("generator") && !name.equals("outputDir") - && !name.equals("owner")) { + && !name.equals("owner") + && !(prov != null && (name.equals("generatedBy") || name.equals("sourceNode")))) { extras.add(name, f.getValue()); } } } JsonElement value; - if (owner == null && extras.size() == 0) { + boolean stamped = prov != null && prov.sourceNode() != null; + if (owner == null && extras.size() == 0 && !stamped) { value = new com.google.gson.JsonPrimitive(e.getValue()); } else { JsonObject entry = new JsonObject(); @@ -338,6 +378,10 @@ public static void save(Path genStateDir, Map hashes, Map f : extras.entrySet()) entry.add(f.getKey(), f.getValue()); + if (stamped) { + entry.addProperty("generatedBy", prov.generatedBy()); + entry.addProperty("sourceNode", prov.sourceNode()); + } value = entry; } String file = placement != null @@ -426,6 +470,22 @@ public static void recordHash(Path genStateDir, String key, String hash, Owner o save(genStateDir, hashes, owners); } + /** + * Record, on each recorded path's entry, the generator that wrote it and the node it was + * rendered from ({@link #save(Path, Map, Map, Placement, Map)} states the entry shapes). A path + * with no recorded hash is left alone: this describes what a write recorded, it never records + * one. Nothing is written when no entry changes. + */ + public static void recordProvenance(Path genStateDir, Map provenance, Placement placement) { + Map hashes = load(genStateDir); + Map applied = new LinkedHashMap<>(); + for (Map.Entry e : provenance.entrySet()) { + if (hashes.containsKey(e.getKey())) applied.put(e.getKey(), e.getValue()); + } + if (applied.isEmpty()) return; + save(genStateDir, hashes, loadOwners(genStateDir), placement, applied); + } + /** The hash recorded for {@code key}, or {@code null} if never recorded. */ public static String recordedHash(Path genStateDir, String key) { return load(genStateDir).get(key); diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java index 5ab8f378f5..a27889161e 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java @@ -119,6 +119,42 @@ public void legacySplit() throws Exception { assertEquals(split.get("gitignoreAfter").getAsString(), Files.readString(gitignore)); } + @Test + public void provenance() throws Exception { + JsonObject v = vectors(); + JsonObject prov = v.getAsJsonObject("provenance"); + Path gs = genState(); + Path dir = gs.resolve(".hashes"); + Files.createDirectories(dir); + for (Map.Entry f : prov.getAsJsonObject("beforeFiles").entrySet()) { + Files.writeString(dir.resolve(f.getKey()), f.getValue().toString()); + } + Map records = new LinkedHashMap<>(); + for (JsonElement el : prov.getAsJsonArray("records")) { + JsonObject r = el.getAsJsonObject(); + records.put(r.get("path").getAsString(), + new HashManifest.Provenance(r.get("generatedBy").getAsString(), nullable(r.get("sourceNode")))); + } + + HashManifest.recordProvenance(gs, records, placement(v)); + + Map written = filesIn(dir); + JsonObject expected = prov.getAsJsonObject("afterFiles"); + assertEquals(new TreeSet<>(expected.keySet()), new TreeSet<>(written.keySet())); + for (String name : expected.keySet()) { + assertEquals(name, expected.get(name), JsonParser.parseString(written.get(name))); + } + assertEquals(prov.get("goldenText").getAsString(), written.get(prov.get("goldenFile").getAsString())); + + // Recording the same records a second time changes no file. + for (Path p : Files.list(dir).toList()) Files.setLastModifiedTime(p, LONG_AGO); + HashManifest.recordProvenance(gs, records, placement(v)); + assertEquals(written, filesIn(dir)); + for (Path p : Files.list(dir).toList()) { + assertEquals(p.toString(), LONG_AGO, Files.getLastModifiedTime(p)); + } + } + @Test public void gitignoreIsTouchedOnlyByAMigratingWrite() throws Exception { Path gs = genState(); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java index 03283bb26c..16e49fc4af 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java @@ -348,11 +348,11 @@ protected CodeWriter.Block openControllerClass(SpringJavaWriter w, List } /** Write the finished controller through the shared write path. */ - protected void writeControllerFile(Path outRoot, String pkg, String controllerName, SpringJavaWriter w, - String failureContext) { + protected void writeControllerFile(MetaObject entity, Path outRoot, String pkg, String controllerName, + SpringJavaWriter w, String failureContext) { try { Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(controllerName + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), entity); } catch (IOException e) { throw new GeneratorException( "failed writing " + failureContext.replace("{file}", controllerName + ".java") + ": " + e, e); @@ -424,7 +424,7 @@ protected void emit(MetaObject entity, Path outRoot) { for (SpringM2mSupport.M2mNav nav : navs) writeM2mHandler(w, entity, nav, pkType); writeParseSortHelper(w, repoName); } - writeControllerFile(outRoot, pkg, controllerName, w, "{file} for entity " + entity.getName()); + writeControllerFile(entity, outRoot, pkg, controllerName, w, "{file} for entity " + entity.getName()); } /** @@ -811,7 +811,7 @@ protected void emitReadOnly(MetaObject entity, Path outRoot) { writeMethodNotAllowed(w, noun); writeParseSortHelper(w, repoName); } - writeControllerFile(outRoot, pkg, controllerName, w, "{file} for " + noun + " " + entity.getName()); + writeControllerFile(entity, outRoot, pkg, controllerName, w, "{file} for " + noun + " " + entity.getName()); } /** @@ -1336,7 +1336,7 @@ protected void emitTph(MetaObject base, TphPlan.Plan plan, Path outRoot) { writeTphNotFound(w); writeParseSortHelper(w, repoName); } - writeControllerFile(outRoot, pkg, controllerName, w, "TPH {file} for entity " + base.getName()); + writeControllerFile(base, outRoot, pkg, controllerName, w, "TPH {file} for entity " + base.getName()); } /** Polymorphic list — the union across all subtypes, each row tagged by its discriminator. */ diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java index 7c07a22190..442c6bb03b 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java @@ -841,7 +841,7 @@ protected SpringJavaWriter newWriter(String pkg) { protected void writeJavaFile(MetaObject entity, Path outRoot, String pkg, String typeName, SpringJavaWriter w) { try { Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(typeName + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), entity); } catch (IOException e) { throw new GeneratorException( "failed writing " + typeName + ".java for entity " + entity.getName() + ": " + e, e); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringFilterAllowlistGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringFilterAllowlistGenerator.java index c7e164ecbd..8c88429053 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringFilterAllowlistGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringFilterAllowlistGenerator.java @@ -281,7 +281,7 @@ protected void emit(MetaObject entity, Path outRoot, MetaDataLoader loader) { try { Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(className + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), entity); } catch (IOException e) { throw new GeneratorException( "failed writing " + className + ".java for entity " + entity.getName() + ": " + e, e); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java index 586b18bc80..7cf2fb04ae 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java @@ -654,7 +654,7 @@ protected boolean emit(MetaObject entity, Path outRoot, String strategy, boolean try { Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(className + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), entity); } catch (IOException e) { throw new GeneratorException( "failed writing " + className + ".java for entity " + entity.getName() + ": " + e, e); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputParserGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputParserGenerator.java index 7bd92da83c..443a0417aa 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputParserGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputParserGenerator.java @@ -240,7 +240,7 @@ protected void emit(MetaTemplate template, MetaDataLoader loader, Path outRoot) try { Path outFile = outRoot.resolve(outPkg.replace('.', '/')).resolve(parserClass + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), template); } catch (IOException e) { throw new GeneratorException( "failed writing " + parserClass + ".java for template " + template.getName() + ": " + e, e); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputPromptGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputPromptGenerator.java index 57d185096c..c54c6bee18 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputPromptGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringOutputPromptGenerator.java @@ -153,7 +153,7 @@ protected void emit(MetaTemplate template, MetaDataLoader loader, Path outRoot) try { Path outFile = outRoot.resolve(outPkg.replace('.', '/')).resolve(promptClass + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), template); } catch (IOException e) { throw new GeneratorException( "failed writing " + promptClass + ".java for template " + template.getName() + ": " + e, e); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java index ec5bcf11f2..b684a77d08 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java @@ -255,7 +255,7 @@ protected void emit(MetaTemplate template, MetaDataLoader loader, Path outRoot, try { Path outFile = outRoot.resolve(outPkg.replace('.', '/')).resolve(helperClass + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), template); } catch (IOException e) { throw new GeneratorException( "failed writing " + helperClass + ".java for template " + template.getName() + ": " + e, e); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringReportExportGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringReportExportGenerator.java index 1609e11efa..5b79fd820e 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringReportExportGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringReportExportGenerator.java @@ -167,12 +167,12 @@ public void execute(MetaDataLoader loader) { String writerPackage = getArg(ARG_WRITER_PACKAGE, sharedPackage(served)); boolean decimalsAsString = loader.getRoot().getWireFormat().decimalsAsString(); - write(outRoot, writerPackage, WRITER_NAME, + write(null, outRoot, writerPackage, WRITER_NAME, writerSource(writerPackage, xmlNulls, csvBom, decimalsAsString, usesDurationCell(served))); for (MetaObject entity : served) { if (!inEntitySelection(entity)) continue; String[] split = SpringNaming.splitFqn(entity.getName()); - write(outRoot, split[0], split[1] + "Export", + write(entity, outRoot, split[0], split[1] + "Export", exportSource(entity, split[0], split[1], writerPackage, maxRows)); } } @@ -194,10 +194,10 @@ static String sharedPackage(List served) { return prefix == null || prefix.length == 0 ? "export" : String.join(".", prefix); } - private static void write(Path outRoot, String pkg, String className, String source) { + private static void write(MetaObject node, Path outRoot, String pkg, String className, String source) { try { Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(className + ".java"); - GeneratedFileWriter.write(outFile, source); + GeneratedFileWriter.write(outFile, source, node); } catch (IOException e) { throw new GeneratorException("failed writing " + className + ".java: " + e, e); } diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRepositoryGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRepositoryGenerator.java index 657633c854..8ef9eb96d6 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRepositoryGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRepositoryGenerator.java @@ -163,7 +163,7 @@ protected void emit(MetaObject entity, Path outRoot) { try { Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(repoName + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), entity); } catch (IOException e) { throw new GeneratorException( "failed writing " + repoName + ".java for entity " + entity.getName() + ": " + e, e); @@ -216,7 +216,7 @@ protected void emitReadOnly(MetaObject entity, Path outRoot) { try { Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(repoName + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), entity); } catch (IOException e) { throw new GeneratorException( "failed writing " + repoName + ".java for " + noun + " " + entity.getName() + ": " + e, e); @@ -301,7 +301,7 @@ protected void emitTph(MetaObject base, Path outRoot) { try { Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(repoName + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), base); } catch (IOException e) { throw new GeneratorException( "failed writing TPH " + repoName + ".java for entity " + base.getName() + ": " + e, e); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java index 263711b1c5..1c335a05be 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java @@ -218,7 +218,7 @@ private void emit(MetaObject vo, Path outRoot) { try { Path outFile = outRoot.resolve(pkg.replace('.', '/')).resolve(recordName + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), vo); } catch (IOException e) { throw new GeneratorException( "failed writing value object " + recordName + ".java for " + vo.getName() + ": " + e, e); diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java index d1c4b059e0..8377e6681f 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java @@ -173,7 +173,9 @@ protected void executeGenerators(MetaDataLoader loader, List generato String handEdits = param != null ? param.validatedHandEdits() : GeneratorParam.HAND_EDITS_KEEP; HashManifest.Owner owner = genStateDir != null && param != null ? ownerOf(param) : null; if (owner != null) runOwners.add(owner); - run.attributeTo( gen.getClass().getSimpleName(), handEdits, owner ); + String generatedBy = param != null && param.getClassname() != null + ? RequiresCheck.generatorName(param.getClassname()) : gen.getClass().getSimpleName(); + run.attributeTo( gen.getClass().getSimpleName(), handEdits, owner, generatedBy ); gen.execute( loader ); if (genStateDir != null && param != null) { diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/RequiresCheck.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/RequiresCheck.java index e602d699e4..b2da83d58c 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/RequiresCheck.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/RequiresCheck.java @@ -66,6 +66,13 @@ static String registryId(String classname) { return k != null ? k.port() + ":" + k.stableName() : classname; } + /** What the manifest's {@code generatedBy} calls {@code classname}: its registry stable name + * ({@code dto}), or its simple class name for a generator of your own. */ + static String generatorName(String classname) { + Known k = resolve(known(), classname); + return k != null ? k.stableName() : EjectSupport.simpleNameOf(classname); + } + /** The registry entry {@code classname} is, or {@code null}: by class name, then by simple name. */ private static Known resolve(List known, String classname) { for (Known k : known) if (k.classname().equals(classname)) return k; diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java new file mode 100644 index 0000000000..3150ae6087 --- /dev/null +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java @@ -0,0 +1,122 @@ +package com.metaobjects.mojo; + +import com.metaobjects.generator.direct.object.javacode.JavaObjectCodeGenerator; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.generator.util.HashManifest; +import org.apache.maven.project.MavenProject; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** Generated-file provenance, end to end: a per-object file names its generator and node; a whole-model file names neither. */ +public class GeneratedProvenanceTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + private Path module; + + private MetaDataGeneratorMojo generate() throws Exception { + return generate(""); + } + + private MetaDataGeneratorMojo generate(String extraChildren) throws Exception { + module = tmp.getRoot().toPath().resolve("module"); + Files.createDirectories(module.resolve("metaobjects")); + Files.writeString(module.resolve("metaobjects/meta.shop.json"), """ + {"metadata.root": {"package": "acme::shop", "children": [ + {"object.entity": {"name": "Order", "children": [ {"field.long": {"name": "id"}} ]}}EXTRA + ]}} + """.replace("EXTRA", extraChildren)); + Files.writeString(module.resolve("metaobjects/meta.crm.json"), """ + {"metadata.root": {"package": "acme::crm", "children": [ + {"object.entity": {"name": "Customer", "children": [ {"field.long": {"name": "id"}} ]}} + ]}} + """); + MetaDataGeneratorMojo mojo = new MetaDataGeneratorMojo(); + MavenProject project = Mockito.mock(MavenProject.class); + Mockito.when(project.getBasedir()).thenReturn(module.toFile()); + mojo.project = project; + mojo.setLoader(LoaderParam.builder("per-package") + .withClassname("com.metaobjects.loader.MetaDataLoader") + .withSourceDir(module.resolve("metaobjects").toString()) + .build()); + mojo.setGenerators(new ArrayList<>(List.of( + GeneratorParam.builder(JavaObjectCodeGenerator.class.getName()) + .withArg("outputDir", "generated").withArg("type", "class").withArg("flavor", "pojoAware").build(), + GeneratorParam.builder(com.metaobjects.generator.spring.SpringValueObjectGenerator.class.getName()) + .withArg("outputDir", "generated-dto").build(), + GeneratorParam.builder(com.metaobjects.generator.spring.SpringDtoGenerator.class.getName()) + .withArg("outputDir", "generated-dto").build()))); + mojo.setGlobals(java.util.Collections.emptyMap()); + return mojo; + } + + private JsonObject entry(String pkgFile, String keySuffix) throws Exception { + Path file = module.resolve(".metaobjects/.gen-state/.hashes").resolve(pkgFile); + JsonObject all = JsonParser.parseString(Files.readString(file)).getAsJsonObject(); + for (String key : all.keySet()) { + if (key.endsWith(keySuffix)) { + JsonElement e = all.get(key); + assertTrue(key + " is an object entry: " + e, e.isJsonObject()); + return e.getAsJsonObject(); + } + } + throw new AssertionError("no " + keySuffix + " in " + all.keySet()); + } + + @Test + public void aPerObjectFileNamesItsGeneratorAndNodeAndAWholeModelFileDoesNot() throws Exception { + generate().execute(); + + JsonObject order = entry("acme.shop.json", "acme/shop/Order.java"); + assertEquals(List.of("hash", "generator", "outputDir", "generatedBy", "sourceNode"), + new ArrayList<>(order.keySet())); + assertEquals("acme::shop::Order", order.get("sourceNode").getAsString()); + assertEquals("java:" + order.get("generatedBy").getAsString(), order.get("generator").getAsString()); + assertEquals("acme::crm::Customer", entry("acme.crm.json", "acme/crm/Customer.java").get("sourceNode").getAsString()); + + // The DTO generator's file is stamped through its own write path, under its own name. + JsonObject dto = entry("acme.shop.json", "OrderDto.java"); + assertEquals("acme::shop::Order", dto.get("sourceNode").getAsString()); + assertEquals("dto", dto.get("generatedBy").getAsString()); + assertEquals("java:dto", dto.get("generator").getAsString()); + + // The META-INF/services file is rendered from the whole model: no provenance fields. + Path dir = module.resolve(".metaobjects/.gen-state/.hashes"); + for (Path p : Files.list(dir).toList()) { + JsonObject all = JsonParser.parseString(Files.readString(p)).getAsJsonObject(); + for (String key : all.keySet()) { + if (key.contains("META-INF")) { + assertFalse(key, all.get(key).isJsonObject() && all.get(key).getAsJsonObject().has("sourceNode")); + } + } + } + } + + @Test + public void aSecondRunWritesNoManifestFile() throws Exception { + generate().execute(); + Path dir = module.resolve(".metaobjects/.gen-state/.hashes"); + List files = Files.list(dir).toList(); + for (Path p : files) Files.setLastModifiedTime(p, java.nio.file.attribute.FileTime.fromMillis(1_000_000_000_000L)); + generate().execute(); + for (Path p : files) { + assertEquals(p.toString(), 1_000_000_000_000L, Files.getLastModifiedTime(p).toMillis()); + } + } +} diff --git a/server/python/src/metaobjects/codegen/generator.py b/server/python/src/metaobjects/codegen/generator.py index e240580736..bf85edc254 100644 --- a/server/python/src/metaobjects/codegen/generator.py +++ b/server/python/src/metaobjects/codegen/generator.py @@ -16,6 +16,13 @@ class EmittedFile: path: str # relative to GenConfig.out_dir content: str # final, formatted Python source generated_by: str = "" # set by the runner from Generator.name + #: The ``resolution_key()`` of the metadata node this file was rendered from + #: (``acme::shop::Order``), recorded beside the file's hash in the manifest under + #: ``.gen-state/.hashes/``. ``per_entity`` sets it for you; a generator rendering one + #: file from one node by other means sets it itself. ``None`` for a file rendered from + #: the whole model or a whole package (a barrel, a docs index). Mirrors codegen-ts's + #: ``EmittedFile.sourceNode``. + source_node: str | None = None #: The default api-surface subdirectory (the cross-port contract's ``api/python``). @@ -140,7 +147,14 @@ def run(ctx: GenContext) -> list[EmittedFile]: if not ctx.matches(e) or not ctx.is_selected(e): continue r = fn(e, ctx) - out.extend(r if isinstance(r, list) else [r]) + # Each file names the object it was rendered from, unless the generator said + # otherwise, so every per-entity generator (owned copies included) records its + # provenance without a line of its own. + key = e.resolution_key() + for f in r if isinstance(r, list) else [r]: + if f.source_node is None: + f.source_node = key + out.append(f) return out return run diff --git a/server/python/src/metaobjects/codegen/generators/extractor_generator.py b/server/python/src/metaobjects/codegen/generators/extractor_generator.py index 7225d024de..7e4f409b29 100644 --- a/server/python/src/metaobjects/codegen/generators/extractor_generator.py +++ b/server/python/src/metaobjects/codegen/generators/extractor_generator.py @@ -270,6 +270,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: f"{_snake_case(tmpl.name)}_extractor", tmpl.resolution_key(), ), content=ruff_format(content), + source_node=tmpl.resolution_key(), ) ) return files diff --git a/server/python/src/metaobjects/codegen/generators/names_generator.py b/server/python/src/metaobjects/codegen/generators/names_generator.py index 44531d4a25..d8d49087a1 100644 --- a/server/python/src/metaobjects/codegen/generators/names_generator.py +++ b/server/python/src/metaobjects/codegen/generators/names_generator.py @@ -640,6 +640,7 @@ def one(entity: MetaObject, *, fragment: bool) -> list[EmittedFile]: f"{_snake_case(entity.name)}_names", entity.resolution_key(), ), content=ruff_format(source), + source_node=entity.resolution_key(), ) ] diff --git a/server/python/src/metaobjects/codegen/generators/output_parser_generator.py b/server/python/src/metaobjects/codegen/generators/output_parser_generator.py index c3bbe471d4..ddb8fbba4e 100644 --- a/server/python/src/metaobjects/codegen/generators/output_parser_generator.py +++ b/server/python/src/metaobjects/codegen/generators/output_parser_generator.py @@ -339,6 +339,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: f"{_snake_case(tmpl.name)}_response_parser", tmpl.resolution_key(), ), content=ruff_format(content), + source_node=tmpl.resolution_key(), ) ) return files diff --git a/server/python/src/metaobjects/codegen/generators/output_prompt_generator.py b/server/python/src/metaobjects/codegen/generators/output_prompt_generator.py index e74001827e..46d64ffc2f 100644 --- a/server/python/src/metaobjects/codegen/generators/output_prompt_generator.py +++ b/server/python/src/metaobjects/codegen/generators/output_prompt_generator.py @@ -158,6 +158,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: f"{_snake_case(tmpl.name)}_response_format", tmpl.resolution_key(), ), content=content, + source_node=tmpl.resolution_key(), ) ) return files diff --git a/server/python/src/metaobjects/codegen/generators/render_helper_generator.py b/server/python/src/metaobjects/codegen/generators/render_helper_generator.py index a3502bc1bb..7c11b59dbe 100644 --- a/server/python/src/metaobjects/codegen/generators/render_helper_generator.py +++ b/server/python/src/metaobjects/codegen/generators/render_helper_generator.py @@ -254,6 +254,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: f"{_snake_case(tmpl.name)}_render_helper", tmpl.resolution_key(), ), content=ruff_format(content), + source_node=tmpl.resolution_key(), ) ) return files diff --git a/server/python/src/metaobjects/codegen/generators/report_export_generator.py b/server/python/src/metaobjects/codegen/generators/report_export_generator.py index 9c137522a8..53cc39b8c5 100644 --- a/server/python/src/metaobjects/codegen/generators/report_export_generator.py +++ b/server/python/src/metaobjects/codegen/generators/report_export_generator.py @@ -257,6 +257,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: content=self.render_report( report, ModuleScope(ctx.config.output_layout, pkg_of(report)) ), + source_node=report.resolution_key(), ) ) return files diff --git a/server/python/src/metaobjects/codegen/generators/template_generator.py b/server/python/src/metaobjects/codegen/generators/template_generator.py index 6a5066965b..0f49d8a85b 100644 --- a/server/python/src/metaobjects/codegen/generators/template_generator.py +++ b/server/python/src/metaobjects/codegen/generators/template_generator.py @@ -45,6 +45,7 @@ def walk(root: Any) -> list[dict]: { "data": build_entity_template_data(o), "output_path": expand_output_pattern(pattern, bare_name(o), package_of(o)), + "source_node": o.resolution_key(), } for o in concrete ] @@ -90,7 +91,11 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: format=self.format, ) ) - files.append(EmittedFile(path=entry["output_path"], content=content)) + files.append( + EmittedFile( + path=entry["output_path"], content=content, source_node=entry.get("source_node") + ) + ) return files diff --git a/server/python/src/metaobjects/codegen/generators/trace_helper_generator.py b/server/python/src/metaobjects/codegen/generators/trace_helper_generator.py index e77f77b25e..58084acd21 100644 --- a/server/python/src/metaobjects/codegen/generators/trace_helper_generator.py +++ b/server/python/src/metaobjects/codegen/generators/trace_helper_generator.py @@ -372,6 +372,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: entity.resolution_key(), ), content=ruff_format(content), + source_node=entity.resolution_key(), ) ) return files diff --git a/server/python/src/metaobjects/codegen/overwrite_policy.py b/server/python/src/metaobjects/codegen/overwrite_policy.py index 9a63beec2c..7e24a91f81 100644 --- a/server/python/src/metaobjects/codegen/overwrite_policy.py +++ b/server/python/src/metaobjects/codegen/overwrite_policy.py @@ -299,7 +299,39 @@ def _load_hashes(gen_state_dir: str) -> dict[str, str]: return hashes -def _save_hashes(gen_state_dir: str, hashes: dict[str, str]) -> None: +#: What produced one generated file: ``(generated_by, source_node)``. ``source_node`` is +#: the ``resolution_key()`` of the node it was rendered from, ``None`` for a file rendered +#: from the whole model or a whole package. Mirrors codegen-ts's ``GeneratedProvenance``. +Provenance = tuple[str, "str | None"] + +#: The manifest fields provenance owns. Every other field on an entry (``hash``, and the +#: JVM's ``generator`` / ``outputDir`` owner, ADR-0060) is kept as it is. +_PROVENANCE_FIELDS = ("generatedBy", "sourceNode") + + +def _with_provenance(existing: object, digest: str, prov: Provenance) -> object: + """The entry for a path recorded with ``digest`` that ``prov`` produced. + + A path with a source node becomes ``{ "hash", , "generatedBy", + "sourceNode" }``; one without keeps (or returns to) the plain ``""``, so a file + rendered from the whole model adds nothing to the committed manifest. ``generatedBy`` is + deliberately not the JVM's ``generator`` field: that one is an ownership claim the + orphan sweep acts on. + """ + rest: dict[str, object] = {} + if isinstance(existing, dict): + rest = {k: v for k, v in existing.items() if k != "hash" and k not in _PROVENANCE_FIELDS} + generated_by, source_node = prov + if source_node is not None: + return {"hash": digest, **rest, "generatedBy": generated_by, "sourceNode": source_node} + return {"hash": digest, **rest} if rest else digest + + +def _save_hashes( + gen_state_dir: str, + hashes: dict[str, str], + provenance: dict[str, Provenance] | None = None, +) -> None: raw = _read_raw(gen_state_dir) # Keys SORTED, because these files are committed. Insertion order would make the # diff — and any merge conflict between two people who both regenerated — depend @@ -307,7 +339,9 @@ def _save_hashes(gen_state_dir: str, hashes: dict[str, str]) -> None: ordered: dict[str, object] = {} for k in sorted(hashes): existing = raw.get(k) - if isinstance(existing, dict): + if provenance is not None and k in provenance: + ordered[k] = _with_provenance(existing, hashes[k], provenance[k]) + elif isinstance(existing, dict): ordered[k] = {**existing, "hash": hashes[k]} else: ordered[k] = hashes[k] @@ -319,6 +353,27 @@ def _save_hashes(gen_state_dir: str, hashes: dict[str, str]) -> None: _write_manifest_file(gen_state_dir, ordered) +def record_generated_provenance(gen_state_dir: str, provenance: dict[str, Provenance]) -> None: + """Record, on each recorded path's manifest entry, the node it was generated from. + + A path with no recorded hash is left alone: this describes what a write recorded, it + never records a write. Nothing is written when no entry changes. Mirrors codegen-ts's + ``recordGeneratedProvenance``. A run's write loop records through + :meth:`HashManifest.note_provenance` instead, so the session's one save carries it. + """ + if not has_hash_manifest(gen_state_dir): + return + hashes = _load_hashes(gen_state_dir) + raw = _read_raw(gen_state_dir) + if all( + _with_provenance(raw.get(k), hashes[k], prov) == raw.get(k) + for k, prov in provenance.items() + if k in hashes + ): + return + _save_hashes(gen_state_dir, hashes, provenance) + + def _manifest_text(entries: dict[str, object]) -> str: return json.dumps({k: entries[k] for k in sorted(entries)}, indent=2) + "\n" @@ -405,6 +460,9 @@ class HashManifest: def __init__(self, gen_state_dir: str) -> None: self.gen_state_dir = gen_state_dir self.hashes: dict[str, str] = _load_hashes(gen_state_dir) + #: Which generator and node produced each path this session recorded, applied to + #: the entries on :meth:`save`. + self.provenance: dict[str, Provenance] = {} # A legacy manifest is migrated by the next write run, even when nothing else changed. self.dirty = os.path.exists(_manifest_path(gen_state_dir)) @@ -430,11 +488,23 @@ def record( if self.hashes.pop(legacy_rel_path, None) is not None: self.dirty = True + def note_provenance(self, rel_path: str, generated_by: str, source_node: str | None) -> None: + """Record which generator, and which node, produced ``rel_path`` (written on save).""" + self.provenance[rel_path] = (generated_by, source_node) + + def _provenance_changes(self) -> bool: + raw = _read_raw(self.gen_state_dir) + return any( + _with_provenance(raw.get(k), self.hashes[k], prov) != raw.get(k) + for k, prov in self.provenance.items() + if k in self.hashes + ) + def save(self) -> bool: """Write the manifest if anything changed. Returns whether it wrote.""" - if not self.dirty: + if not self.dirty and not (self.provenance and self._provenance_changes()): return False - _save_hashes(self.gen_state_dir, self.hashes) + _save_hashes(self.gen_state_dir, self.hashes, self.provenance) self.dirty = False return True diff --git a/server/python/src/metaobjects/codegen/runner.py b/server/python/src/metaobjects/codegen/runner.py index 8e3d68f566..a1f1da37bf 100644 --- a/server/python/src/metaobjects/codegen/runner.py +++ b/server/python/src/metaobjects/codegen/runner.py @@ -194,6 +194,8 @@ def is_selected(o: MetaObject) -> bool: claims = NameClaims() # one registry per run, shared by every generator emitted: dict[str, tuple[str, str]] = {} # full_path -> (content, generated_by) + # full_path -> the resolution key of the node the file was rendered from, when it was. + sources: dict[str, str] = {} for gen in generators: ctx = GenContext( entities=safe, @@ -214,6 +216,8 @@ def is_selected(o: MetaObject) -> bool: f"{emitted[full][1]!r} and {gen.name!r}." ) emitted[full] = (f.content, gen.name) + if f.source_node is not None: + sources[full] = f.source_node if config.output_layout == OUTPUT_LAYOUT_PACKAGE: assert_importable_package_tree( @@ -263,7 +267,7 @@ def is_selected(o: MetaObject) -> bool: with manifest_batch(config.gen_state_dir): try: _write_all( - config, emitted, merge_strategy, session, result, refused, adopted + config, emitted, sources, merge_strategy, session, result, refused, adopted ) finally: if own_session and session is not None: @@ -274,6 +278,7 @@ def is_selected(o: MetaObject) -> bool: def _write_all( config: GenConfig, emitted: dict[str, tuple[str, str]], + sources: dict[str, str], merge_strategy: str, session: HashManifest | None, result: RunGenResult, @@ -325,6 +330,11 @@ def _write_all( manifest=None if outside else session, ) result.files.append((full, status)) + # Which node each recorded file came from, beside its hash (the docs view's files). + # Only with a real project root, as codegen-ts: the entry is keyed by the same key + # the write used, and the session's save applies it to entries that hold a hash. + if session is not None and not outside and config.project_root: + session.note_provenance(key, by, sources.get(full)) if status == STATUS_OVERWROTE_EDIT: result.warnings.append( f"overwrote hand-edited {rel} with fresh output (handEdits: overwrite on {by})" diff --git a/server/python/tests/codegen/test_gen_unchanged.py b/server/python/tests/codegen/test_gen_unchanged.py index 1d8f5c2a22..f38c448502 100644 --- a/server/python/tests/codegen/test_gen_unchanged.py +++ b/server/python/tests/codegen/test_gen_unchanged.py @@ -71,9 +71,9 @@ def test_manifest_is_saved_once_per_run_and_only_when_it_changed( saves: list[int] = [] real = overwrite_policy._save_hashes - def counting(gen_state_dir: str, hashes: dict[str, str]) -> None: + def counting(gen_state_dir: str, hashes: dict[str, str], provenance: object = None) -> None: saves.append(len(hashes)) - real(gen_state_dir, hashes) + real(gen_state_dir, hashes, provenance) # type: ignore[arg-type] monkeypatch.setattr(overwrite_policy, "_save_hashes", counting) assert main(["gen"]) == 0 @@ -131,9 +131,9 @@ def test_non_prompt_targets_rewrite_nothing_and_save_no_manifest_when_unchanged( saves: list[int] = [] real = overwrite_policy._save_hashes - def counting(gen_state_dir: str, hashes: dict[str, str]) -> None: + def counting(gen_state_dir: str, hashes: dict[str, str], provenance: object = None) -> None: saves.append(len(hashes)) - real(gen_state_dir, hashes) + real(gen_state_dir, hashes, provenance) # type: ignore[arg-type] monkeypatch.setattr(overwrite_policy, "_save_hashes", counting) assert main(["gen"]) == 0 diff --git a/server/python/tests/codegen/test_manifest_store.py b/server/python/tests/codegen/test_manifest_store.py index a60a5632e1..c2ac7d7fde 100644 --- a/server/python/tests/codegen/test_manifest_store.py +++ b/server/python/tests/codegen/test_manifest_store.py @@ -176,6 +176,85 @@ def test_gen_on_a_multi_package_model_writes_one_manifest_per_package(tmp_path: assert len(keys) == len(set(keys)) +def _seed_files(state: Path, files: dict[str, dict[str, object]]) -> Path: + directory = state / ".hashes" + directory.mkdir(parents=True, exist_ok=True) + for name, entries in files.items(): + (directory / name).write_text(json.dumps(entries, indent=2) + "\n") + return directory + + +def _snapshot(directory: Path) -> dict[str, tuple[bytes, int]]: + return {p.name: (p.read_bytes(), p.stat().st_mtime_ns) for p in sorted(directory.glob("*.json"))} + + +def _provenance_records() -> dict[str, tuple[str, str | None]]: + return {r["path"]: (r["generatedBy"], r.get("sourceNode")) for r in VECTORS["provenance"]["records"]} + + +def _assert_provenance_after(directory: Path) -> None: + vector = VECTORS["provenance"] + assert manifest_files(directory.parent) == vector["afterFiles"] + assert (directory / vector["goldenFile"]).read_text() == vector["goldenText"] + + +def test_provenance_vectors(tmp_path: Path) -> None: + state = _state(tmp_path) + directory = _seed_files(state, VECTORS["provenance"]["beforeFiles"]) + set_placement_objects(str(state), OBJECTS) + op.record_generated_provenance(str(state), _provenance_records()) + _assert_provenance_after(directory) + + before = _snapshot(directory) + op.record_generated_provenance(str(state), _provenance_records()) + assert _snapshot(directory) == before, "the same records a second time change no file" + + +def test_provenance_vectors_through_a_run_session(tmp_path: Path) -> None: + # The write loop records through the session, whose one save carries the provenance. + state = _state(tmp_path) + directory = _seed_files(state, VECTORS["provenance"]["beforeFiles"]) + set_placement_objects(str(state), OBJECTS) + session = HashManifest(str(state)) + for path, (by, node) in _provenance_records().items(): + session.note_provenance(path, by, node) + assert session.save() + _assert_provenance_after(directory) + + before = _snapshot(directory) + again = HashManifest(str(state)) + for path, (by, node) in _provenance_records().items(): + again.note_provenance(path, by, node) + assert not again.save(), "nothing changed, so nothing is written" + assert _snapshot(directory) == before + + +def test_gen_records_the_generator_and_node_of_each_per_entity_file(tmp_path: Path) -> None: + meta = tmp_path / "metaobjects" + meta.mkdir() + (meta / "meta.shop.json").write_text(json.dumps({"metadata.root": { + "package": "acme::shop", + "children": [{"object.entity": {"name": "Order", "children": [ + {"field.long": {"name": "id"}}, {"field.string": {"name": "title"}}]}}], + }})) + out = tmp_path / "gen" + argv = as_config(["gen", "--generators", GEN_SUITE, str(meta), "--out", str(out)]) + assert main(argv) == 0 + state = tmp_path / ".metaobjects" / ".gen-state" + entries = read_manifest(state) + model = entries["gen/Order.py"] + assert isinstance(model, dict) + assert list(model) == ["hash", "generatedBy", "sourceNode"] + assert (model["generatedBy"], model["sourceNode"]) == ("entity-model", "acme::shop::Order") + # A file of no one node (a package __init__) stays a plain hash. + inits = [v for k, v in entries.items() if k.endswith("__init__.py")] + assert inits and all(isinstance(v, str) for v in inits) + + before = _snapshot(state / ".hashes") + assert main(argv) == 0 + assert _snapshot(state / ".hashes") == before, "a regeneration that changes nothing writes nothing" + + @pytest.mark.parametrize( ("before", "after"), [ diff --git a/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts b/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts index 2b655bfc3d..438c7ef8f8 100644 --- a/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts +++ b/server/typescript/packages/codegen-ts/test/hash-manifest-store.test.ts @@ -9,7 +9,13 @@ import { placeEntry, readManifestState, } from "../src/hash-manifest-store.js"; -import { forgetGeneratedPaths, listGeneratedPaths, withManifestBatch, writeManifestFiles } from "../src/overwrite-policy.js"; +import { + forgetGeneratedPaths, + listGeneratedPaths, + recordGeneratedProvenance, + withManifestBatch, + writeManifestFiles, +} from "../src/overwrite-policy.js"; import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; interface Vectors { @@ -24,6 +30,13 @@ interface Vectors { gitignoreBefore: string; gitignoreAfter: string; }; + provenance: { + beforeFiles: Record>; + records: { path: string; generatedBy: string; sourceNode?: string }[]; + afterFiles: Record>; + goldenFile: string; + goldenText: string; + }; } const VECTORS = JSON.parse( @@ -76,6 +89,31 @@ describe("shared vectors", () => { expect(files().map((f) => statSync(join(dirOf(), f)).mtimeMs)).toEqual(before); }); + test("provenance: each recorded path names its generator and node, and is placed by it", () => { + const { beforeFiles, records, afterFiles, goldenFile, goldenText } = VECTORS.provenance; + mkdirSync(dirOf(), { recursive: true }); + for (const [name, entries] of Object.entries(beforeFiles)) { + writeFileSync(join(dirOf(), name), JSON.stringify(entries, null, 2) + "\n"); + } + const record = (): void => withManifestBatch(state, () => { + recordGeneratedProvenance(state, new Map(records.map((r) => [r.path, { + generatedBy: r.generatedBy, + ...(r.sourceNode !== undefined && { sourceNode: r.sourceNode }), + }]))); + }, VECTORS.objects); + record(); + expect(files()).toEqual(Object.keys(afterFiles).sort()); + for (const [name, entries] of Object.entries(afterFiles)) expect(read(name)).toEqual(entries); + expect(readFileSync(join(dirOf(), goldenFile), "utf-8")).toBe(goldenText); + + // The same records a second time change no file. + const before = files().map((f) => readFileSync(join(dirOf(), f), "utf-8")); + const stamps = files().map((f) => statSync(join(dirOf(), f)).mtimeMs); + record(); + expect(files().map((f) => readFileSync(join(dirOf(), f), "utf-8"))).toEqual(before); + expect(files().map((f) => statSync(join(dirOf(), f)).mtimeMs)).toEqual(stamps); + }); + test("the gitignore rewrite replaces the legacy negation, or adds one after .gen-state/*", () => { const ignore = join(tmp, ".metaobjects", ".gitignore"); const cases: [string, string][] = [ diff --git a/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md b/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md index 4128748892..8bfa619523 100644 --- a/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md +++ b/spec/decisions/ADR-0064-skip-codegen-when-nothing-changed.md @@ -153,7 +153,7 @@ replace), one JSON file per model package: - A file holds exactly what the single manifest held for its paths, unchanged: one JSON object keyed by project-relative path, keys sorted, two-space indentation, a trailing newline, each value a SHA-256 hex string or an object carrying `hash` and any owner or provenance fields the port keeps - (`generator` and `outputDir` on the JVM, `generatedBy` and `sourceNode` in TypeScript). Nothing + (`generator` and `outputDir` on the JVM, `generatedBy` and `sourceNode` in TypeScript, C#, Java and Python). Nothing about a value changes, so no reader of one entry changes. **2. Reading is a union.** A reader merges every `*.json` file in `.hashes/`, in file-name order, with @@ -166,7 +166,7 @@ entry costs a merge conflict that could have been avoided and nothing else. **3. Placement is a pure function, so it is stable.** A writer files each entry under: -1. **Its recorded `sourceNode`**, when it has one (TypeScript records it). The package is the +1. **Its recorded `sourceNode`**, when it has one (TypeScript, C#, Java and Python record it). The package is the `sourceNode` up to its first `.`, minus its last `::` segment (`acme::shop::Order.id` files under `acme::shop`). A `sourceNode` with no `::` names an object in no package: the root manifest. 2. **Else the object whose name the file's stem begins with, word by word.** The stem is the file's From 189bc1e6aa488debc42dcfe0073e581d75e9951f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 27 Nov 2026 19:57:32 -0500 Subject: [PATCH 02/13] no-mistakes(review): Stamp provenance in remaining per-object generators --- .../HashManifestPerPackageTests.cs | 53 ++++++++++++ .../Generators/FilterAllowlistGenerator.cs | 2 +- .../Generators/NamesGenerator.cs | 2 +- .../Generators/RoutesGenerator.cs | 4 +- .../generator/template/ScopeWalk.java | 3 +- .../template/TemplateScopeGenerator.java | 2 +- .../generator/util/GeneratedFileWriter.java | 5 ++ .../generator/util/HashManifest.java | 16 ---- .../util/HashManifestPackagesTest.java | 83 ++++++++++++++++--- .../mustache/MustacheTemplateGenerator.java | 2 +- .../spring/LlmTraceHelperGenerator.java | 2 +- .../mojo/GeneratedProvenanceTest.java | 79 ++++++++++++++++++ .../render/templategen/EmittedFile.java | 10 ++- .../render/templategen/TemplateGenerator.java | 2 +- .../templategen/TemplateWalkResult.java | 10 ++- .../metaobjects/codegen/overwrite_policy.py | 21 ----- .../tests/codegen/test_manifest_store.py | 12 --- 17 files changed, 236 insertions(+), 72 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs index 78704a12a7..3e311abf92 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/HashManifestPerPackageTests.cs @@ -172,6 +172,59 @@ public void The_real_entity_generator_stamps_its_entity_file_with_provenance() Assert.True(entry.TryGetProperty("hash", out _)); } + [Fact] + public void The_names_filter_allowlist_and_routes_generators_stamp_each_object_file() + { + var src = """ + { "metadata.root": { "package": "acme::shop", "children": [ + { "object.entity": { "name": "Stamped", "abstract": true, "children": [ + { "field.long": { "name": "id" } }, + { "field.timestamp": { "name": "createdAt" } } ] } }, + { "object.entity": { "name": "Order", "extends": "Stamped", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.string": { "name": "code", "@filterable": true } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, + { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ + { "source.rdb": { "@table": "auths" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "type", "@values": ["Bridge"] } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, + { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ + { "field.int": { "name": "quantity" } } ] } } + ]}} + """; + var r = new MetaDataLoader().Load([new InMemoryStringSource(src, id: "shop.json")]); + Assert.Empty(r.Errors); + var config = new GenConfig + { + OutDir = Path.Combine(_root, "gen"), Namespace = "Probe", GenStateDir = StateDir, ProjectRoot = _root, + }; + CodegenRunner.Run(config, r.Root, + [ + new MetaObjects.Codegen.Generators.NamesGenerator(), + new MetaObjects.Codegen.Generators.FilterAllowlistGenerator(), + new MetaObjects.Codegen.Generators.RoutesGenerator(), + ]); + + using var shop = JsonDocument.Parse(File.ReadAllText(Path.Combine(HashesDir, "acme.shop.json"))); + var stamped = shop.RootElement.EnumerateObject() + .ToDictionary(p => p.Name, p => p.Value.ValueKind == JsonValueKind.Object + ? $"{p.Value.GetProperty("generatedBy").GetString()} {Str(p.Value, "sourceNode")}" + : "(plain)"); + Assert.Equal(new Dictionary + { + ["gen/AuthFilterAllowlist.g.cs"] = "filter-allowlist-generator acme::shop::Auth", + ["gen/AuthNames.g.cs"] = "names acme::shop::Auth", + ["gen/AuthRoutes.g.cs"] = "routes-generator acme::shop::Auth", + ["gen/BridgeAuthFilterAllowlist.g.cs"] = "filter-allowlist-generator acme::shop::BridgeAuth", + ["gen/BridgeAuthNames.g.cs"] = "names acme::shop::BridgeAuth", + ["gen/OrderFilterAllowlist.g.cs"] = "filter-allowlist-generator acme::shop::Order", + ["gen/OrderNames.g.cs"] = "names acme::shop::Order", + ["gen/OrderRoutes.g.cs"] = "routes-generator acme::shop::Order", + ["gen/StampedNames.g.cs"] = "names acme::shop::Stamped", + }, stamped); + } + private sealed class WholeModelFile : IGenerator { public string Name => "barrel"; diff --git a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs index 67fad041cc..48521000d7 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs @@ -113,7 +113,7 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) } } - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}FilterAllowlist.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}FilterAllowlist.g.cs"), w.ToString()) { SourceNode = entity.ResolutionKey() }; } // The pieces of the file, one overridable method each (ADR-0063 item 7): a subclass changes the diff --git a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs index 1b54c6b156..7c9f95412b 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs @@ -387,7 +387,7 @@ private static HashSet InheritedMembers(MetaObject obj, ColumnNamingStra WriteColumnsByField(w, names, hasBase: superCls is not null); } - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{cls}.g.cs"), w.ToString()) { SourceNode = entity.ResolutionKey() }; } // The pieces of the file, one overridable method each (ADR-0063 item 7): a subclass changes the diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index 48f2d06644..cf797a8126 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -402,7 +402,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte WriteOmitResultClass(w, p.Credentials.Count > 0 || (p.HasItem && M2mTargetHasCredentials([entity], ctx.Root, ctx.Config))); w.Close("}"); - return new EmittedFile(OutputPaths.Of(entity, ctx, $"{p.Cls}Routes.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(entity, ctx, $"{p.Cls}Routes.g.cs"), w.ToString()) { SourceNode = entity.ResolutionKey() }; } ///

@@ -799,7 +799,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t WriteOmitResultClass(w, p.BaseCredentials.Count > 0 || (p.HasItem && M2mTargetHasCredentials(p.Hierarchy, ctx.Root, ctx.Config))); w.Close("}"); - return new EmittedFile(OutputPaths.Of(baseEntity, ctx, $"{baseCls}Routes.g.cs"), w.ToString()); + return new EmittedFile(OutputPaths.Of(baseEntity, ctx, $"{baseCls}Routes.g.cs"), w.ToString()) { SourceNode = baseEntity.ResolutionKey() }; } /// The polymorphic list, GET /<base>: the union of all subtypes, each row carrying its discriminator. diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/ScopeWalk.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/ScopeWalk.java index cf188bb2a3..3613a715ab 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/ScopeWalk.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/ScopeWalk.java @@ -35,7 +35,8 @@ public static Function, List> forScope( for (MetaObject o : concrete) { out.add(new TemplateWalkResult( TemplateData.entity(o), - OutputPattern.expand(outputPattern, TemplateData.bareName(o), TemplateData.packageOf(o)))); + OutputPattern.expand(outputPattern, TemplateData.bareName(o), TemplateData.packageOf(o)), + com.metaobjects.generator.util.GeneratedFileWriter.resolutionKey(o))); } return out; case PER_PACKAGE: { diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java index f4078e0920..8f1bb61b68 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java @@ -83,7 +83,7 @@ public void execute(MetaDataLoader loader) { // SQL, markdown, CSV, anything — and that content carries no obligation to // include the `GENERATED` marker. It is still recorded in the hash manifest, so // unchanged bytes are not rewritten and a hand edit is refused by name. - com.metaobjects.generator.util.GeneratedFileWriter.writeUnmarked(target, f.content()); + com.metaobjects.generator.util.GeneratedFileWriter.writeUnmarked(target, f.content(), f.sourceNode()); } catch (IOException e) { throw new GeneratorException( "Failed to write template-codegen output [" + target + "]: " + e.getMessage(), e); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java index 7cdfa0fcb6..9486106d97 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java @@ -465,6 +465,11 @@ public static Outcome writeUnmarked(Path outFile, String content, MetaData sourc return writeFrom(sourceNode == null ? null : resolutionKey(sourceNode), outFile, content, true); } + /** {@link #writeUnmarked(Path, String, MetaData)} for a caller that holds the node's resolution key, not the node. */ + public static Outcome writeUnmarked(Path outFile, String content, String sourceNodeKey) throws IOException { + return writeFrom(sourceNodeKey, outFile, content, true); + } + private static Outcome writeFrom(String sourceNodeKey, Path outFile, String content, boolean unmarked) throws IOException { Run run = ACTIVE_RUN.get(); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java index 4fc6ac5b04..eba31da290 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/HashManifest.java @@ -470,22 +470,6 @@ public static void recordHash(Path genStateDir, String key, String hash, Owner o save(genStateDir, hashes, owners); } - /** - * Record, on each recorded path's entry, the generator that wrote it and the node it was - * rendered from ({@link #save(Path, Map, Map, Placement, Map)} states the entry shapes). A path - * with no recorded hash is left alone: this describes what a write recorded, it never records - * one. Nothing is written when no entry changes. - */ - public static void recordProvenance(Path genStateDir, Map provenance, Placement placement) { - Map hashes = load(genStateDir); - Map applied = new LinkedHashMap<>(); - for (Map.Entry e : provenance.entrySet()) { - if (hashes.containsKey(e.getKey())) applied.put(e.getKey(), e.getValue()); - } - if (applied.isEmpty()) return; - save(genStateDir, hashes, loadOwners(genStateDir), placement, applied); - } - /** The hash recorded for {@code key}, or {@code null} if never recorded. */ public static String recordedHash(Path genStateDir, String key) { return load(genStateDir).get(key); diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java index a27889161e..a682ed0726 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/HashManifestPackagesTest.java @@ -119,26 +119,53 @@ public void legacySplit() throws Exception { assertEquals(split.get("gitignoreAfter").getAsString(), Files.readString(gitignore)); } + /** + * The vectors' placeholder hashes stand for real files: each path that has one is given + * content whose hash replaces it, so a gen run's write path can leave the file unchanged + * and record only what it rendered the file from. A record for a path with no recorded + * hash is a write the run never makes, so it is not made. + */ @Test public void provenance() throws Exception { JsonObject v = vectors(); JsonObject prov = v.getAsJsonObject("provenance"); + Path root = tmp.getRoot().toPath(); Path gs = genState(); Path dir = gs.resolve(".hashes"); Files.createDirectories(dir); + Map realHashes = new LinkedHashMap<>(); + Map contentByPath = new LinkedHashMap<>(); + Map ownerByPath = new LinkedHashMap<>(); for (Map.Entry f : prov.getAsJsonObject("beforeFiles").entrySet()) { - Files.writeString(dir.resolve(f.getKey()), f.getValue().toString()); - } - Map records = new LinkedHashMap<>(); - for (JsonElement el : prov.getAsJsonArray("records")) { - JsonObject r = el.getAsJsonObject(); - records.put(r.get("path").getAsString(), - new HashManifest.Provenance(r.get("generatedBy").getAsString(), nullable(r.get("sourceNode")))); + JsonObject entries = f.getValue().deepCopy().getAsJsonObject(); + for (Map.Entry e : entries.entrySet()) { + String path = e.getKey(); + JsonElement entry = e.getValue(); + String placeholder = entry.isJsonObject() + ? entry.getAsJsonObject().get("hash").getAsString() : entry.getAsString(); + String content = "// GENERATED content of " + path + "\n"; + String hash = HashManifest.contentHash(content); + realHashes.put(hash, placeholder); + contentByPath.put(path, content); + Files.createDirectories(root.resolve(path).getParent()); + Files.writeString(root.resolve(path), content); + if (entry.isJsonObject()) { + JsonObject o = entry.getAsJsonObject(); + o.addProperty("hash", hash); + if (o.has("generator")) { + ownerByPath.put(path, new HashManifest.Owner( + o.get("generator").getAsString(), o.get("outputDir").getAsString())); + } + } else { + entries.addProperty(path, hash); + } + } + Files.writeString(dir.resolve(f.getKey()), entries.toString()); } - HashManifest.recordProvenance(gs, records, placement(v)); + runProvenanceRecords(prov, root, gs, placement(v), contentByPath, ownerByPath); - Map written = filesIn(dir); + Map written = placeholdersIn(filesIn(dir), realHashes); JsonObject expected = prov.getAsJsonObject("afterFiles"); assertEquals(new TreeSet<>(expected.keySet()), new TreeSet<>(written.keySet())); for (String name : expected.keySet()) { @@ -146,15 +173,47 @@ public void provenance() throws Exception { } assertEquals(prov.get("goldenText").getAsString(), written.get(prov.get("goldenFile").getAsString())); - // Recording the same records a second time changes no file. + // The same run a second time changes no file. + Map before = filesIn(dir); for (Path p : Files.list(dir).toList()) Files.setLastModifiedTime(p, LONG_AGO); - HashManifest.recordProvenance(gs, records, placement(v)); - assertEquals(written, filesIn(dir)); + runProvenanceRecords(prov, root, gs, placement(v), contentByPath, ownerByPath); + assertEquals(before, filesIn(dir)); for (Path p : Files.list(dir).toList()) { assertEquals(p.toString(), LONG_AGO, Files.getLastModifiedTime(p)); } } + private static void runProvenanceRecords(JsonObject prov, Path root, Path gs, HashManifest.Placement placement, + Map contentByPath, + Map ownerByPath) throws IOException { + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.configureManifest(gs, root).placeBy(placement); + for (JsonElement el : prov.getAsJsonArray("records")) { + JsonObject r = el.getAsJsonObject(); + String path = r.get("path").getAsString(); + String content = contentByPath.get(path); + if (content == null) continue; + String by = r.get("generatedBy").getAsString(); + run.attributeTo(by, GeneratedFileWriter.HAND_EDITS_KEEP, ownerByPath.get(path), by); + String node = nullable(r.get("sourceNode")); + GeneratedFileWriter.Outcome outcome = node == null + ? GeneratedFileWriter.write(root.resolve(path), content) + : GeneratedFileWriter.write(root.resolve(path), content, node); + assertEquals(path, GeneratedFileWriter.Outcome.UNCHANGED, outcome); + } + } + } + + private static Map placeholdersIn(Map files, Map realHashes) { + Map out = new LinkedHashMap<>(); + for (Map.Entry f : files.entrySet()) { + String text = f.getValue(); + for (Map.Entry h : realHashes.entrySet()) text = text.replace(h.getKey(), h.getValue()); + out.put(f.getKey(), text); + } + return out; + } + @Test public void gitignoreIsTouchedOnlyByAMigratingWrite() throws Exception { Path gs = genState(); diff --git a/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java b/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java index f1d541bbed..d864c436b8 100644 --- a/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java +++ b/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java @@ -298,7 +298,7 @@ private void generateFileFromTemplate(MetaObject metaObject, TemplateDefinition // user template's output, in a format we do not choose. Path outputPath = Paths.get(outputDir, packagePath); File outputFile = outputPath.resolve(fileName).toFile(); - com.metaobjects.generator.util.GeneratedFileWriter.writeUnmarked(outputFile.toPath(), generatedCode); + com.metaobjects.generator.util.GeneratedFileWriter.writeUnmarked(outputFile.toPath(), generatedCode, metaObject); log.debug("Generated file: {}", outputFile.getAbsolutePath()); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/LlmTraceHelperGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/LlmTraceHelperGenerator.java index c44ad58c62..48352ae494 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/LlmTraceHelperGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/LlmTraceHelperGenerator.java @@ -228,7 +228,7 @@ protected void emit(MetaObject entity, MetaDataLoader loader, Path outRoot) { Path outFile = pkg.isEmpty() ? outRoot.resolve(helperClass + ".java") : outRoot.resolve(pkg.replace('.', '/')).resolve(helperClass + ".java"); - GeneratedFileWriter.write(outFile, w.toString()); + GeneratedFileWriter.write(outFile, w.toString(), entity); } catch (IOException e) { throw new GeneratorException( "failed writing " + helperClass + ".java for entity " + entity.getName() + ": " + e, e); diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java index 3150ae6087..793eb1dfb1 100644 --- a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java @@ -108,6 +108,85 @@ public void aPerObjectFileNamesItsGeneratorAndNodeAndAWholeModelFileDoesNot() th } } + @Test + public void theTraceHelperTemplateAndMustacheGeneratorsStampEachPerObjectFile() throws Exception { + module = tmp.getRoot().toPath().resolve("module"); + Files.createDirectories(module.resolve("metaobjects")); + Files.writeString(module.resolve("metaobjects/meta.shop.json"), """ + {"metadata.root": {"package": "acme::shop", "children": [ + {"object.value": {"name": "GreetRequest", "children": [ {"field.string": {"name": "name"}} ]}}, + {"object.value": {"name": "GreetResponse", "children": [ {"field.string": {"name": "greeting"}} ]}}, + {"object.entity": {"name": "GreetingCall", "extends": "metaobjects::ai::LlmCallBase", "children": [ + {"source.rdb": {"@table": "greeting_call", "@role": "primary"}}, + {"identity.primary": {"name": "pk", "@fields": ["spanId"]}}, + {"template.prompt": {"name": "greetingPrompt", + "@payloadRef": "acme::shop::GreetRequest", "@responseRef": "acme::shop::GreetResponse"}} ]}} + ]}} + """); + Files.createDirectories(module.resolve("templates")); + Files.writeString(module.resolve("templates/one.mustache"), "{{name}}\n"); + Files.writeString(module.resolve("templates/all.mustache"), "model\n"); + Files.writeString(module.resolve("templates/names.mustache.yaml"), """ + name: "Names" + version: "1.0.0" + targetLanguage: "java" + outputFileExtension: "txt" + packagePath: false + template: | + {{className}} + """); + MetaDataGeneratorMojo mojo = new MetaDataGeneratorMojo(); + MavenProject project = Mockito.mock(MavenProject.class); + Mockito.when(project.getBasedir()).thenReturn(module.toFile()); + mojo.project = project; + LoaderParam loader = LoaderParam.builder("per-object") + .withClassname("com.metaobjects.loader.MetaDataLoader") + .withSourceDir(module.resolve("metaobjects").toString()) + .build(); + loader.setLibraries(List.of("ai")); + mojo.setLoader(loader); + mojo.setGenerators(new ArrayList<>(List.of( + GeneratorParam.builder(com.metaobjects.generator.spring.LlmTraceHelperGenerator.class.getName()) + .withArg("outputDir", "generated-trace").build(), + GeneratorParam.builder(com.metaobjects.generator.template.TemplateScopeGenerator.class.getName()) + .withArg("outputDir", "generated-template").withArg("templatesDir", "templates") + .withArg("template", "one").withArg("scope", "perEntity") + .withArg("outputPattern", "{Name}.txt").build(), + GeneratorParam.builder(com.metaobjects.generator.template.TemplateScopeGenerator.class.getName()) + .withArg("outputDir", "generated-template").withArg("templatesDir", "templates") + .withArg("template", "all").withArg("scope", "perModel") + .withArg("outputPattern", "model.txt").build(), + GeneratorParam.builder(com.metaobjects.generator.mustache.MustacheTemplateGenerator.class.getName()) + .withArg("outputDir", module.resolve("generated-mustache").toString()) + .withArg("templatePath", module.resolve("templates").toString()) + .withArg("templateName", "names").build()))); + mojo.setGlobals(java.util.Collections.emptyMap()); + mojo.execute(); + + assertEquals("acme::shop::GreetingCall", + entry("acme.shop.json", "acme/shop/GreetingCallTraceHelper.java").get("sourceNode").getAsString()); + assertEquals("acme::shop::GreetingCall", + entry("acme.shop.json", "generated-template/GreetingCall.txt").get("sourceNode").getAsString()); + assertEquals("acme::shop::GreetRequest", + entry("acme.shop.json", "generated-mustache/GreetRequest.txt").get("sourceNode").getAsString()); + assertEquals("acme::shop::GreetingCall", + entry("acme.shop.json", "generated-mustache/GreetingCall.txt").get("sourceNode").getAsString()); + + // The per-model template file is rendered from the whole model: no sourceNode. + Path dir = module.resolve(".metaobjects/.gen-state/.hashes"); + boolean seen = false; + for (Path p : Files.list(dir).toList()) { + JsonObject all = JsonParser.parseString(Files.readString(p)).getAsJsonObject(); + for (String key : all.keySet()) { + if (key.endsWith("generated-template/model.txt")) { + seen = true; + assertFalse(key, all.get(key).isJsonObject() && all.get(key).getAsJsonObject().has("sourceNode")); + } + } + } + assertTrue("the per-model template file is recorded", seen); + } + @Test public void aSecondRunWritesNoManifestFile() throws Exception { generate().execute(); diff --git a/server/java/render/src/main/java/com/metaobjects/render/templategen/EmittedFile.java b/server/java/render/src/main/java/com/metaobjects/render/templategen/EmittedFile.java index 4f8df62666..759a89ee0c 100644 --- a/server/java/render/src/main/java/com/metaobjects/render/templategen/EmittedFile.java +++ b/server/java/render/src/main/java/com/metaobjects/render/templategen/EmittedFile.java @@ -8,5 +8,13 @@ *

This is NOT the legacy {@code com.metaobjects.generator.Generator} contract * (which writes via {@code execute()} side-effects); this record exists because * the cross-port template-generator factory returns its files declaratively. + * + *

{@code sourceNode} is the resolution key of the one metadata node the file was rendered + * from, recorded in the hash manifest; {@code null} for a per-package or per-model file. */ -public record EmittedFile(String path, String content) {} +public record EmittedFile(String path, String content, String sourceNode) { + /** A file rendered from the whole model or a package: no {@code sourceNode}. */ + public EmittedFile(String path, String content) { + this(path, content, null); + } +} diff --git a/server/java/render/src/main/java/com/metaobjects/render/templategen/TemplateGenerator.java b/server/java/render/src/main/java/com/metaobjects/render/templategen/TemplateGenerator.java index 7c6c9cb426..f6cf1a0424 100644 --- a/server/java/render/src/main/java/com/metaobjects/render/templategen/TemplateGenerator.java +++ b/server/java/render/src/main/java/com/metaobjects/render/templategen/TemplateGenerator.java @@ -56,7 +56,7 @@ public static List generate( /* verify */ null, /* maxChars */ null); String content = renderer.render(req); - out.add(new EmittedFile(entry.outputPath(), content)); + out.add(new EmittedFile(entry.outputPath(), content, entry.sourceNode())); } return out; } diff --git a/server/java/render/src/main/java/com/metaobjects/render/templategen/TemplateWalkResult.java b/server/java/render/src/main/java/com/metaobjects/render/templategen/TemplateWalkResult.java index 6efd3c3e7d..62e9bf85bd 100644 --- a/server/java/render/src/main/java/com/metaobjects/render/templategen/TemplateWalkResult.java +++ b/server/java/render/src/main/java/com/metaobjects/render/templategen/TemplateWalkResult.java @@ -3,5 +3,13 @@ /** * One walk entry: a payload + the output path the rendered template should * be emitted to (relative to whatever output root the caller chooses). + * + *

{@code sourceNode} is the resolution key of the node a per-entity entry was walked from; + * {@code null} for a per-package or per-model entry. */ -public record TemplateWalkResult(Object data, String outputPath) {} +public record TemplateWalkResult(Object data, String outputPath, String sourceNode) { + /** An entry walked from no single node. */ + public TemplateWalkResult(Object data, String outputPath) { + this(data, outputPath, null); + } +} diff --git a/server/python/src/metaobjects/codegen/overwrite_policy.py b/server/python/src/metaobjects/codegen/overwrite_policy.py index 7e24a91f81..2fa432370b 100644 --- a/server/python/src/metaobjects/codegen/overwrite_policy.py +++ b/server/python/src/metaobjects/codegen/overwrite_policy.py @@ -353,27 +353,6 @@ def _save_hashes( _write_manifest_file(gen_state_dir, ordered) -def record_generated_provenance(gen_state_dir: str, provenance: dict[str, Provenance]) -> None: - """Record, on each recorded path's manifest entry, the node it was generated from. - - A path with no recorded hash is left alone: this describes what a write recorded, it - never records a write. Nothing is written when no entry changes. Mirrors codegen-ts's - ``recordGeneratedProvenance``. A run's write loop records through - :meth:`HashManifest.note_provenance` instead, so the session's one save carries it. - """ - if not has_hash_manifest(gen_state_dir): - return - hashes = _load_hashes(gen_state_dir) - raw = _read_raw(gen_state_dir) - if all( - _with_provenance(raw.get(k), hashes[k], prov) == raw.get(k) - for k, prov in provenance.items() - if k in hashes - ): - return - _save_hashes(gen_state_dir, hashes, provenance) - - def _manifest_text(entries: dict[str, object]) -> str: return json.dumps({k: entries[k] for k in sorted(entries)}, indent=2) + "\n" diff --git a/server/python/tests/codegen/test_manifest_store.py b/server/python/tests/codegen/test_manifest_store.py index c2ac7d7fde..411d9eb595 100644 --- a/server/python/tests/codegen/test_manifest_store.py +++ b/server/python/tests/codegen/test_manifest_store.py @@ -198,18 +198,6 @@ def _assert_provenance_after(directory: Path) -> None: assert (directory / vector["goldenFile"]).read_text() == vector["goldenText"] -def test_provenance_vectors(tmp_path: Path) -> None: - state = _state(tmp_path) - directory = _seed_files(state, VECTORS["provenance"]["beforeFiles"]) - set_placement_objects(str(state), OBJECTS) - op.record_generated_provenance(str(state), _provenance_records()) - _assert_provenance_after(directory) - - before = _snapshot(directory) - op.record_generated_provenance(str(state), _provenance_records()) - assert _snapshot(directory) == before, "the same records a second time change no file" - - def test_provenance_vectors_through_a_run_session(tmp_path: Path) -> None: # The write loop records through the session, whose one save carries the provenance. state = _state(tmp_path) From f964f8184d38909c987cee06756c7a7dc4f2af10 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 27 Nov 2026 20:07:45 -0500 Subject: [PATCH 03/13] no-mistakes(document): Docs for C#/Java/Python provenance already updated on branch; one wording fix. --- docs/features/explorer-data.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/features/explorer-data.md b/docs/features/explorer-data.md index 79055782f5..962f5c1dac 100644 --- a/docs/features/explorer-data.md +++ b/docs/features/explorer-data.md @@ -119,8 +119,8 @@ 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" }`. Every port writes the same entry for the same records; the shared -vector `provenance` in +"generatedBy", "sourceNode" }`. The four 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. From f3c6e89a27fbe90cb963a2f0fae9fd990cd72a4b Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 02:00:57 -0500 Subject: [PATCH 04/13] no-mistakes(test): Stop identifier renaming in explorer bundle build --- changelog.d/explorer-app-stable-bundle.md | 7 +++++++ explorer-app/README.md | 3 ++- explorer-app/assets/explorer-app.js | 16 ++++++++-------- .../ExplorerApp/assets/explorer-app.js | 16 ++++++++-------- .../explorer-app/assets/explorer-app.js | 16 ++++++++-------- .../explorer_app/assets/explorer-app.js | 16 ++++++++-------- .../docs-site/app/assets/explorer-app.js | 16 ++++++++-------- .../packages/docs-site/scripts/build-app.ts | 9 ++++++--- 8 files changed, 55 insertions(+), 44 deletions(-) create mode 100644 changelog.d/explorer-app-stable-bundle.md diff --git a/changelog.d/explorer-app-stable-bundle.md b/changelog.d/explorer-app-stable-bundle.md new file mode 100644 index 0000000000..34ea61646b --- /dev/null +++ b/changelog.d/explorer-app-stable-bundle.md @@ -0,0 +1,7 @@ +- **The explorer app's bundle builds the same bytes every time.** `explorer-app/assets/explorer-app.js` + is now minified for whitespace and syntax only, and keeps its identifiers' names. Bun's choice of + short names was not stable between builds of unchanged sources, so the check that the committed + bundle is what the sources build failed at random. The bundle grows from about 95 KB to about + 120 KB. Every port's copy is refreshed, so the docs site's `assets/explorer-app.js` changes and + nothing else does. Generated-output change — regenerate to pick it up; three-way merge preserves + hand edits. diff --git a/explorer-app/README.md b/explorer-app/README.md index 7d53080ebd..41d6f759a3 100644 --- a/explorer-app/README.md +++ b/explorer-app/README.md @@ -16,7 +16,8 @@ bash scripts/sync-explorer-app.sh # refres The `explorer app copies` step of `scripts/ci-local.sh --only gates` fails when this directory is stale or a port's copy differs from it. -The bundle is minified, and minified output depends on the Bun version, so `build-app.ts` runs +The bundle is minified for whitespace and syntax only. Identifiers keep their names, because +Bun's short names are not stable between builds. Minified output depends on the Bun version, so `build-app.ts` runs only on the Bun the workflows pin (`EXPLORER_APP_BUN` in the script, currently 1.3.14). Any other Bun stops with an error that names the required version. diff --git a/explorer-app/assets/explorer-app.js b/explorer-app/assets/explorer-app.js index 3a52a6d4e0..dd2a04d098 100644 --- a/explorer-app/assets/explorer-app.js +++ b/explorer-app/assets/explorer-app.js @@ -11,7 +11,7 @@ * * 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. */ -(()=>{var V3={"explorer-head.mustache":` +(()=>{var explorer_templates_default={"explorer-head.mustache":` @@ -260,10 +260,10 @@ `};/*! * mustache.js - Logic-less {{mustache}} templates with JavaScript * http://github.com/janl/mustache.js - */var DH=Object.prototype.toString,Gh=Array.isArray||function(H){return DH.call(H)==="[object Array]"};function m3(h){return typeof h==="function"}function FH(h){return Gh(h)?"array":typeof h}function d3(h){return h.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function o3(h,H){return h!=null&&typeof h==="object"&&H in h}function YH(h,H){return h!=null&&typeof h!=="object"&&h.hasOwnProperty&&h.hasOwnProperty(H)}var MH=RegExp.prototype.test;function kH(h,H){return MH.call(h,H)}var lH=/\S/;function gH(h){return!kH(lH,h)}var UH={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function SH(h){return String(h).replace(/[&<>"'`=\/]/g,function(q){return UH[q]})}var xH=/\s*/,LH=/\s+/,e3=/\s*=/,NH=/\s*\}/,fH=/#|\^|\/|>|\{|&|=|!/;function OH(h,H){if(!h)return[];var q=!1,$=[],Z=[],z=[],K=!1,b=!1,J="",V=0;function W(){if(K&&!b)while(z.length)delete Z[z.pop()];else z=[];K=!1,b=!1}var y,w,v;function l(Q){if(typeof Q==="string")Q=Q.split(LH,2);if(!Gh(Q)||Q.length!==2)throw Error("Invalid tags: "+Q);y=new RegExp(d3(Q[0])+"\\s*"),w=new RegExp("\\s*"+d3(Q[1])),v=new RegExp("\\s*"+d3("}"+Q[1]))}l(H||p.tags);var k=new Mh(h),D,g,F,d,B,C;while(!k.eos()){if(D=k.pos,F=k.scanUntil(y),F)for(var Y=0,j=F.length;Y")B=[g,F,D,k.pos,J,V,q];else B=[g,F,D,k.pos];if(V++,Z.push(B),g==="#"||g==="^")$.push(B);else if(g==="/"){if(C=$.pop(),!C)throw Error('Unopened section "'+F+'" at '+D);if(C[1]!==F)throw Error('Unclosed section "'+C[1]+'" at '+D)}else if(g==="name"||g==="{"||g==="&")b=!0;else if(g==="=")l(F)}if(W(),C=$.pop(),C)throw Error('Unclosed section "'+C[1]+'" at '+k.pos);return AH(PH(Z))}function PH(h){var H=[],q,$;for(var Z=0,z=h.length;Z0?$[$.length-1][4]:H;break;default:q.push(Z)}return H}function Mh(h){this.string=h,this.tail=h,this.pos=0}Mh.prototype.eos=function(){return this.tail===""};Mh.prototype.scan=function(H){var q=this.tail.match(H);if(!q||q.index!==0)return"";var $=q[0];return this.tail=this.tail.substring($.length),this.pos+=$.length,$};Mh.prototype.scanUntil=function(H){var q=this.tail.search(H),$;switch(q){case-1:$=this.tail,this.tail="";break;case 0:$="";break;default:$=this.tail.substring(0,q),this.tail=this.tail.substring(q)}return this.pos+=$.length,$};function yh(h,H){this.view=h,this.cache={".":this.view},this.parent=H}yh.prototype.push=function(H){return new yh(H,this)};yh.prototype.lookup=function(H){var q=this.cache,$;if(q.hasOwnProperty(H))$=q[H];else{var Z=this,z,K,b,J=!1;while(Z){if(H.indexOf(".")>0){z=Z.view,K=H.split("."),b=0;while(z!=null&&b")V=this.renderPartial(b,q,$,z);else if(J==="&")V=this.unescapedValue(b,q);else if(J==="name")V=this.escapedValue(b,q,z);else if(J==="text")V=this.rawValue(b);if(V!==void 0)K+=V}return K};O.prototype.renderSection=function(H,q,$,Z,z){var K=this,b="",J=q.lookup(H[1]);function V(w){return K.render(w,q,$,z)}if(!J)return;if(Gh(J))for(var W=0,y=J.length;W0||!$))z[K]=Z+z[K];return z.join(` -`)};O.prototype.renderPartial=function(H,q,$,Z){if(!$)return;var z=this.getConfigTags(Z),K=m3($)?$(H[1]):$[H[1]];if(K!=null){var b=H[6],J=H[5],V=H[4],W=K;if(J==0&&V)W=this.indentPartial(K,V,b);var y=this.parse(W,z);return this.renderTokens(y,q,$,W,Z)}};O.prototype.unescapedValue=function(H,q){var $=q.lookup(H[1]);if($!=null)return $};O.prototype.escapedValue=function(H,q,$){var Z=this.getConfigEscape($)||p.escape,z=q.lookup(H[1]);if(z!=null)return typeof z==="number"&&Z===p.escape?String(z):Z(z)};O.prototype.rawValue=function(H){return H[1]};O.prototype.getConfigTags=function(H){if(Gh(H))return H;else if(H&&typeof H==="object")return H.tags;else return};O.prototype.getConfigEscape=function(H){if(H&&typeof H==="object"&&!Gh(H))return H.escape;else return};var p={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(h){Yh.templateCache=h},get templateCache(){return Yh.templateCache}},Yh=new O;p.clearCache=function(){return Yh.clearCache()};p.parse=function(H,q){return Yh.parse(H,q)};p.render=function(H,q,$,Z){if(typeof H!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+FH(H)+'" was given as the first argument for mustache#render(template, view, partials)');return Yh.render(H,q,$,Z)};p.escape=SH;p.Scanner=Mh;p.Context=yh;p.Writer=O;var Hh=p;var y3=(h)=>h.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),IH=/^-?[0-9]+(\.[0-9]+)?$/,H2=(h)=>/^[=+\-@\t\r]/.test(h)&&!IH.test(h)?"'"+h:h,RH=(h)=>{let H=H2(h);return/[",\n\r]/.test(H)?`"${H.replace(/"/g,'""')}"`:H},iH=(h)=>JSON.stringify(h).slice(1,-1),h2=(h)=>h,q2={text:h2,markdown:h2,html:y3,xml:y3,json:iH,csv:RH,spreadsheet:(h)=>H2(y3(h))};var $2="has";function ah(h){return"has"+cH(h)}var kh="-last";function cH(h){if(h.length===0)return h;let H=h.charAt(0);if(H===H.toUpperCase()&&H!==H.toLowerCase())return h;return H.toUpperCase()+h.slice(1)}function Z2(h){if(h===null||h===void 0)return!1;if(typeof h==="string")return h.trim().length>0;if(Array.isArray(h))return h.length>0;if(typeof h==="number"||typeof h==="boolean"||typeof h==="bigint")return;return typeof h==="object"}function z2(h,H=0){return lh(h,H,void 0)}function lh(h,H,q){if(H>32)return h;if(Array.isArray(h)){let K=h.length-1;return h.map((b,J)=>lh(b,H+1,J===K))}if(h===null||typeof h!=="object")return h;let $=Object.getPrototypeOf(h);if($!==Object.prototype&&$!==null)return sH(h,H,q);let Z=h,z={};for(let[K,b]of Object.entries(Z))z[K]=lh(b,H+1,void 0);for(let[K,b]of Object.entries(Z)){let J=ah(K);if(Object.prototype.hasOwnProperty.call(Z,J))continue;let V=Z2(b);if(V!==void 0)z[J]=V}if(q!==void 0&&!Object.prototype.hasOwnProperty.call(Z,kh))z[kh]=q;return z}function pH(h){return h.length===0?h:h.charAt(0).toLowerCase()+h.slice(1)}function sH(h,H,q){let $=new Map,Z=(K)=>{if($.has(K))return $.get(K);let b=Reflect.get(h,K,h),J=typeof b==="function"?(...V)=>lh(Reflect.apply(b,h,V),H+1,void 0):lh(b,H+1,void 0);return $.set(K,J),J},z=(K)=>{if(typeof K!=="string")return;if(K===kh)return q;if(!K.startsWith("has"))return;let b=K.slice(3);for(let J of[pH(b),b]){if(!(J in h)||ah(J)!==K)continue;let V=Reflect.get(h,J,h);if(typeof V==="function")continue;let W=Z2(V);if(W!==void 0)return W}return};return new Proxy(Object.create(null),{has:(K,b)=>(b in h)||z(b)!==void 0,get:(K,b)=>(b in h)?Z(b):z(b)})}var b2=["mustache","jinja"],gh="mustache",e="jinja";var K2=[".jinja",".j2",".jinja2"];function qh(h,H,q){let $=h.engineOf?.(H);return $!==void 0&&$!==q}function th(h,H){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${h} is not a ${H} template; a ${H} body includes only ${H} partials`}function X2(h,H,q){if(q!==void 0){if(!b2.includes(q))throw Error(`unknown template engine ${JSON.stringify(q)}; expected one of ${b2.join(", ")}`);return q}if(h!==void 0&&H!==void 0){let $=h.engineOf?.(H);if($!==void 0)return $}return"mustache"}var R="ERR_VAR_NOT_ON_PAYLOAD",Uh="ERR_PARTIAL_UNRESOLVED",G3="ERR_REQUIRED_SLOT_UNUSED";var Sh="ERR_TEMPLATE_NOT_STATIC",$h="ERR_TEMPLATE_SYNTAX",xh="ERR_TEMPLATE_ENGINE_UNSUPPORTED",t=32,aH=new Set([">"," ","\t",` -`,"\r"]);function tH(h,H){let q=`<${H}`;for(let $=h.indexOf(q);$!==-1;$=h.indexOf(q,$+1)){let Z=h[$+q.length];if(Z!==void 0&&aH.has(Z))return!0}return!1}function nH(h,H){return h.includes(``)}function nh(h,H,q){let $=[];for(let z of q?.requiredSlots??[])if(!h.has(z))$.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:z});let Z=q?.requiredTags??[];if(Z.length>0){let z=H.join(` -`);for(let K of Z)if(!tH(z,K)||!nH(z,K))$.push({code:"ERR_OUTPUT_TAG_MISSING",path:K})}return $}var _H=()=>{throw Error("the explorer app renders Mustache only")},C3=new Proxy({},{get:()=>_H});var Zh=C3;function Lh(h){return Zh.parser.parse(h)}function zh(h){return typeof h==="object"&&h!==null&&typeof h.typename==="string"}function I(h){let H=[],q=($)=>{if(Array.isArray($))$.forEach(q);else if(zh($))H.push($)};for(let $ of h.fields)q(h[$]);if(h.typename==="Set")q(h.body);return H}function Nh(h){for(let H of K2)if(h.toLowerCase().endsWith(H))return h.slice(0,-H.length);return h}function TH(h){return function(H,q){this._emit("runtime.markSafe("),h.call(this,H,q),this._emit(")")}}function EH(h){let H={getSource(q){let $=h.resolve(Nh(q));return $===void 0?null:{src:$,path:q,noCache:!0}}};return new C3.Environment(H,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function rH(h){if(h===void 0)throw Error(`render verify failed: ${R}`);return h}function W2(h,H,q,$){let Z=EH(q),z=Zh.compiler.Compiler.prototype,K=Zh.lib.escape,b=z.compileCapture,J=Zh.runtime.ensureDefined;Zh.runtime.ensureDefined=rH,Zh.lib.escape=(V)=>$(typeof V==="string"?V:String(V)),z.compileCapture=TH(b);try{return Z.renderString(h,H)}finally{Zh.lib.escape=K,z.compileCapture=b,Zh.runtime.ensureDefined=J}}var S={tag:"opaque"},oH=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),eH=new Set(["first","last","random"]),hq=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),Hq=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),qq="attribute";function J2(h,H){return{tag:"typed",fields:h.fields,isArray:h.isArray===!0,path:H}}function Q2(h,H){if(h.tag==="opaque")return S;return{tag:"typed",fields:h.isArray?h.fields:void 0,isArray:!1,path:H}}function u3(h){if(h.kind==="key")return`.${h.key}`;if(h.kind==="index")return`[${h.index}]`;return"[*]"}function j2(h,H,q){let $=[],Z=q?.provider,z=new Set,K=[h],b=(j,Q)=>{$.push({code:j,path:Q})};function J(j,Q){for(let G=Q.frames.length-1;G>=0;G--){let u=Q.frames[G].get(j);if(u!==void 0)return u}let m=Q.root.find((G)=>G.name===j);if(m!==void 0){if(Q.root===H)z.add(j);return J2(m,j)}return oH.has(j)?S:void 0}function V(j,Q,m){j.frames[j.frames.length-1].set(Q,m)}function W(j){return{...j,frames:[...j.frames,new Map]}}function y(j){let Q=[],m=j;while(m.typename==="LookupVal"){let G=m.val;if(G.typename==="Literal"&&typeof G.value==="string")Q.unshift({kind:"key",key:G.value});else if(G.typename==="Literal"&&typeof G.value==="number")Q.unshift({kind:"index",index:G.value});else Q.unshift({kind:"dynamic",node:G});m=m.target}return{base:m,segments:Q}}function w(j,Q){let{base:m,segments:G}=y(j);for(let L of G)if(L.kind==="dynamic")B(L.node,Q);let u,M;if(m.typename==="Symbol"){M=m.value;let L=M+G.map(u3).join(""),c=J(M,Q);if(c===void 0)return b(R,L),S;u=c}else u=B(m,Q),M=u.tag==="typed"?u.path:"";let s=M+G.map(u3).join("");for(let L of G){if(u.tag==="opaque")return S;if(M+=u3(L),L.kind==="key"){let c=u.isArray?void 0:u.fields?.find((mh)=>mh.name===L.key);if(c===void 0)return b(R,s),S;u=J2(c,M)}else if(u.isArray)u={tag:"typed",fields:u.fields,isArray:!1,path:M};else if(L.kind==="dynamic"&&u.fields!==void 0)return b(Sh,s),S;else u={tag:"typed",fields:u.fields,isArray:!1,path:M}}return u}function v(j,Q,m){if(j.tag==="opaque"){B(Q,m);return}if(Q.typename!=="Literal"||typeof Q.value!=="string"){B(Q,m),b(Sh,`${j.path}[*]`);return}let G=Q.value,u=j.fields;for(let M of G.split(".")){let s=u?.find((L)=>L.name===M);if(s===void 0){b(R,`${j.path}.${G}`);return}u=s.fields}}function l(j){let Q=[],m=[];for(let G of j===void 0?[]:I(j))if(G.typename==="KeywordArgs")for(let u of I(G)){let M=u.key;m.push([String(M.value),u.value])}else Q.push(G);return{positional:Q,keywords:m}}function k(j,Q){let m=String(j.name.value),{positional:G,keywords:u}=l(j.args),[M,...s]=G,L=M===void 0?S:B(M,Q);s.forEach((c,mh)=>{if(mh===Hq.get(m))v(L,c,Q);else B(c,Q)});for(let[c,mh]of u)if(c===qq)v(L,mh,Q);else B(mh,Q);if(eH.has(m))return L.tag==="typed"?Q2(L,`${L.path}|${m}`):S;if(hq.has(m))return L;return S}function D(j,Q){let m=j.name;if(m.typename==="LookupVal")B(m.target,Q);else if(m.typename==="Symbol"){let M=m.value;if(J(M,Q)===void 0)b(R,M)}else B(m,Q);let{positional:G,keywords:u}=l(j.args);return G.forEach((M)=>B(M,Q)),u.forEach(([,M])=>B(M,Q)),S}function g(j,Q){let m=W(Q);for(let G of["caller","varargs","kwargs"])V(m,G,S);for(let G of I(j.args))if(G.typename==="Symbol")V(m,G.value,S);else if(G.typename==="KeywordArgs")for(let u of I(G))B(u.value,Q),V(m,String(u.key.value),S);C(j.body,m)}function F(j,Q,m,G,u=!1){if(Q.typename!=="Literal"||typeof Q.value!=="string"){B(Q,m),b(Sh,j);return}if(Z===void 0)return;let M=Nh(Q.value);if(m.seen.includes(M)||m.seen.length>=t)return;let s=Z.resolve(M);if(s===void 0){if(!u)b(Uh,M);return}if(qh(Z,M,e)){b(xh,M);return}K.push(s);let L;try{L=Lh(s)}catch(c){b($h,`${M}: ${c.message}`);return}C(L,G(m,M))}function d(j,Q,m){if(j.typename==="Symbol")V(m,j.value,Q);else for(let G of I(j))d(G,S,m)}function B(j,Q){switch(j.typename){case"Symbol":case"LookupVal":return w(j,Q);case"Literal":case"TemplateData":return S;case"Group":{let m=I(j);if(m.length===1)return B(m[0],Q);return m.forEach((G)=>B(G,Q)),S}case"Filter":case"FilterAsync":return k(j,Q);case"FunCall":return D(j,Q);case"Caller":return g(j,Q),S;case"Is":{B(j.left,Q);let m=j.right;if(m.typename==="FunCall"){let{positional:G,keywords:u}=l(m.args);G.forEach((M)=>B(M,Q)),u.forEach(([,M])=>B(M,Q))}return S}case"Pair":{let m=j.key;if(m.typename!=="Symbol")B(m,Q);return B(j.value,Q),S}case"Capture":return C(j.body,Q),S;default:for(let m of I(j))B(m,Q);return S}}function C(j,Q){switch(j.typename){case"Root":case"NodeList":for(let m of I(j))C(m,Q);return;case"Output":for(let m of I(j))B(m,Q);return;case"If":case"IfAsync":{if(B(j.cond,Q),C(j.body,Q),zh(j.else_))C(j.else_,Q);return}case"For":case"AsyncEach":case"AsyncAll":{let m=B(j.arr,Q),G=W(Q);V(G,"loop",S);let u=j.name;if(u.typename==="Symbol"){let M=u.value;V(G,M,Q2(m,M))}else d(u,S,G);if(C(j.body,G),zh(j.else_))C(j.else_,Q);return}case"Set":{let m=j.targets.filter(zh),G=S;if(zh(j.value))G=B(j.value,Q);else if(zh(j.body))B(j.body,Q);for(let u of m){let M=u.value;V(Q,M,G.tag==="typed"&&m.length===1?{...G,path:M}:S)}return}case"Macro":V(Q,String(j.name.value),S),g(j,Q);return;case"Include":F("include",j.template,Q,(m,G)=>({...W(m),seen:[...m.seen,G]}),j.ignoreMissing===!0);return;case"Import":case"FromImport":{let m=j.withContext===!0;if(F("import",j.template,Q,(G,u)=>({frames:[new Map],root:m?H:[],seen:[...G.seen,u]})),j.typename==="Import")V(Q,String(j.target.value),S);else for(let G of I(j.names)){let u=G.typename==="Pair"?G.value:G;V(Q,String(u.value),S)}return}case"Extends":F("extends",j.template,Q,(m,G)=>({frames:[new Map],root:H,seen:[...m.seen,G]}));return;case"Block":C(j.body,Q);return;case"Switch":{B(j.expr,Q);for(let m of I(j.cases))B(m.cond,Q),C(m.body,Q);if(zh(j.default))C(j.default,Q);return}default:B(j,Q)}}let Y;try{Y=Lh(h)}catch(j){return[{code:$h,path:j.message}]}return C(Y,{frames:[new Map],root:H,seen:[]}),$.push(...nh(z,K,q)),$}function w2(h,H){if(H.includes("."))return!1;if(!H.startsWith($2))return!1;for(let q=h.length-1;q>=0;q--)for(let $ of h[q])if(H===ah($.name))return!0;return!1}function V2(h,H){return h&&H===kh}function d2(h,H){return h.find((q)=>q.name===H)}function $q(h,H){let q=H.split("."),$;for(let Z=h.length-1;Z>=0;Z--){let z=d2(h[Z],q[0]);if(z){$=z;break}}for(let Z=1;$&&ZH[0]===Zq).map((H)=>[H[1],H[2],H[3]])}function Kq(h){return Th(h).some((H)=>H[0]===bq)}function _h(h,H){if(!Kq(h))return;return H??B3(h)[0]?.[0]}function Xq(h){return Th(h).filter((H)=>H[0]===zq).map((H)=>[H[2],H[3]])}function G2(h,H){let q="",$=0;for(let[Z,z]of Xq(H))q+=h.slice($,Z),$=z;return q+h.slice($)}function Wq(h){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(h instanceof Error?h.message:"")?.[1]}function u2(h){return C2(h)}function B2(h,H,q){if(q?.engine===e)return j2(h,H,q);let $=[],Z=q?.provider,z=H,K=new Set,b=[h];function J(y,w,v,l=!1){let k=w.length===1&&w[0]===z;for(let D of y){let g=D[0],F=D[1];switch(g){case"name":case"&":case"{":{if(F===".")break;if(k)K.add(F.split(".")[0]);if(!m2(w,F)&&!w2(w,F)&&!V2(l,F))$.push({code:R,path:F});break}case"#":case"^":{let d=Array.isArray(D[4])?D[4]:[];if(F==="."){J(d,w,v,l);break}if(k)K.add(F.split(".")[0]);let B=m2(w,F);if(!B){if(V2(l,F)){J(d,w,v,l);break}if(w2(w,F)){J(d,w,v,l);break}$.push({code:R,path:F});break}let C=g==="#"&&B.fields!==void 0,Y=g==="#"&&B.isArray===!0;J(d,C?[...w,B.fields]:w,v,Y?B.fields!==void 0:l);break}case">":{if(!Z)break;if(v.includes(F)||v.length>=t)break;let d=Z.resolve(F);if(d===void 0){$.push({code:Uh,path:F});break}if(qh(Z,F,gh)){$.push({code:xh,path:F});break}let B=y2(d);if(!Array.isArray(B)){$.push(B);break}let C=_h(B,F);if(C!==void 0)$.push({code:$h,path:C});b.push(G2(d,B)),J(B,w,[...v,F],l);break}default:break}}}let V=y2(h);if(!Array.isArray(V))return[V];let W=_h(V,void 0);if(W!==void 0)$.push({code:$h,path:W});return b[0]=G2(h,V),J(V,[z],[]),$.push(...nh(K,b,q)),$}var Jq=new Set(["Include","Import","FromImport","Extends"]);function v2(h,H){if(Jq.has(h.typename)){let q=h.template;if(q.typename==="Literal"&&typeof q.value==="string")H.push({ref:Nh(q.value),optional:h.ignoreMissing===!0})}for(let q of I(h))v2(q,H)}function D2(h,H,q){let $=[];v2(Lh(h),$);for(let{ref:Z,optional:z}of $){if(q.includes(Z))throw Error(`partial cycle: ${[...q,Z].join(" -> ")}`);if(q.length>=t)throw Error(`partial depth exceeded ${t}: ${Z}`);let K=H.resolve(Z);if(K===void 0){if(z)continue;throw Error(`unresolved partial: ${Z}`)}if(qh(H,Z,e))throw Error(th(Z,e));D2(K,H,[...q,Z])}}function F2(h,H,q,$,Z){return D2(h,$,H!==void 0?[H]:[]),W2(h,typeof q==="object"&&q!==null?q:{},$,Z)}function Y2(h,H,q,$){let Z=u2(h);if(_h(Z,$)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let z=B3(Z);if(z.length===0)return h;let K="",b=0;for(let[J,V,W]of z){if(q.includes(J))throw Error(`partial cycle: ${[...q,J].join(" -> ")}`);if(q.length>=t)throw Error(`partial depth exceeded ${t}: ${J}`);let y=H.resolve(J);if(y===void 0)throw Error(`unresolved partial: ${J}`);if(qh(H,J,gh))throw Error(th(J,gh));K+=h.slice(b,V)+Y2(y,H,[...q,J],J),b=W}return K+h.slice(b)}function v3(h){let H=h.template??(h.ref!==void 0?h.provider.resolve(h.ref):void 0);if(H===void 0)throw Error(`unresolved ref: ${h.ref??"(none)"}`);let q=X2(h.provider,h.template===void 0?h.ref:void 0,h.engine);if(h.verify!==void 0){let z=B2(H,h.verify,{provider:h.provider,engine:q}).filter((K)=>K.code!==G3);if(z.length>0)throw Error(`render verify failed: ${z.map((K)=>`${K.code} (${K.path})`).join(", ")}`)}let $=q2[h.format??"text"],Z=q===e?F2(H,h.template===void 0?h.ref:void 0,h.payload,h.provider,$):jq(H,h,$);if(h.maxChars!==void 0&&Z.length>h.maxChars)throw Error(`render exceeded maxChars budget: ${Z.length} > ${h.maxChars}`);return Z}function Qq(){let h=Hh.Writer.prototype,H={escapedValue:h.escapedValue,unescapedValue:h.unescapedValue};for(let q of["escapedValue","unescapedValue"]){let $=H[q];h[q]=function(Z,z,...K){let b=String(Z[1]);if(z.lookup(b)===void 0)throw Error(`render verify failed: ${R} (${b})`);return $.call(this,Z,z,...K)}}return()=>{h.escapedValue=H.escapedValue,h.unescapedValue=H.unescapedValue}}function jq(h,H,q){let $=Y2(h,H.provider,H.ref!==void 0?[H.ref]:[]),Z=Hh.escape;Hh.escape=(b)=>q(typeof b==="string"?b:String(b));let z,K=Qq();try{z=Hh.render($,z2(H.payload),{})}finally{Hh.escape=Z,K()}return z}class Eh{map;engine;constructor(h,H={}){this.map=h;this.engine=H.engine}resolve(h){return Object.prototype.hasOwnProperty.call(this.map,h)?this.map[h]:void 0}engineOf(h){return this.resolve(h)===void 0?void 0:this.engine}}var rh="object",oh="field";var eh="identity",h3="relationship",M2="layout",k2="source",D3="origin",H3="template",F3="index",bh="requirement",fh="dimension",Oh="measure",Ph="segment";var Wh="description",l2="summary";var Ch="string";var g2="currency",Ah="enum",U2="uuid",S2="uri",x2="inet",L2="duration";var Y3="required";var M3="default",k3="maxLength";var N2="filterable",f2="sortable";var q3="objectRef";var l3="values";var g3="fields";var U3="references";var S3="entity",O2="value",P2="projection",A2="report";var $3="from",I2="dimensions",R2="measures",i2="segment",x3="filter",c2="spine";var N="eq",P="ne",n="gt",_="gte",T="lt",E="lte",A="in",L3="like",f="isNull";var R1={string:[N,P,A,L3,f],[Ah]:[N,P,A,L3,f],int:[N,P,n,_,T,E,A,f],long:[N,P,n,_,T,E,A,f],double:[N,P,n,_,T,E,A,f],float:[N,P,n,_,T,E,A,f],decimal:[N,P,n,_,T,E,A,f],[g2]:[N,P,n,_,T,E,A,f],boolean:[N,f],date:[N,P,n,_,T,E,A,f],time:[N,P,n,_,T,E,A,f],timestamp:[N,P,n,_,T,E,A,f],[U2]:[N,P,A,f],[S2]:[N,P,A,L3,f],[x2]:[N,P,A,f],[L2]:[N,P,n,_,T,E,A,f]};var wq="association",Vq="aggregation",dq="composition";var p2="cardinality",s2="objectRef",a2="through";var p1={[dq]:"cascade",[Vq]:"set-null",[wq]:"restrict"};var i="functional",Jh="architectural";var Z3="disposition",t2="trackedBy",uh="statement",n2="counterexample";var Qh="planned",Ih="live",N3="partial",f3="retired",_2=["planned","live","partial","retired"];var T2=["planned","partial"];var O3=3,P3=4;var z3="from";var E2="agg",b3="of",A3="via",I3="filter";var R3="expr";var mq=["count","sum","avg","min","max"];var r2="any",o2="all",yq="collect",E1=[...mq,r2,o2,yq];var e2="of",hH="via",HH="grains",qH="agg";var i3="filter",$H="segment",ZH="numerator",zH="denominator";var c3="default";var bH="column";var Gq="uuid",Cq="jsonb";var uq="text",Bq="varchar",vq="character varying";var Z5={[Gq]:[Ch],[Cq]:[Ch],[uq]:[Ch],[Bq]:[Ch],[vq]:[Ch]};var KH="table",XH="view";var WH="kind";var JH="view";var p3="pageSize",QH="defaultSortField",s3="defaultSortOrder";var jH="columns";var a3="prompt";var Rh="payloadRef",wH="textRef",K3="format";var X3="responseRef",VH="maxTokens";var dH="model";var mH="promptStyle";var yH="responseFormat";var jh=[Ih,N3,Qh,f3].filter((h)=>_2.includes(h)),t3={[Ih]:"●",[N3]:"◐",[Qh]:"○",[f3]:"⊘"},GH=(h,H)=>hH?1:0;class n3{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(h){this.view=h;for(let H of h.nodes){let q=this.file(H,H.package,void 0);this.topOf.set(H.id,H);for(let $ of H.memberGroups)for(let Z of $.members)this.fileMember(Z,H.package,q.id);if(H.type===rh)this.objects.push(q);else if(H.type===H3)this.templates.push(q);else if(H.type!==bh)this.others.push(q)}for(let H of this.kids.values())H.sort((q,$)=>q.order-$.order||GH(q.id,$.id));this.packages=h.packages.map((H)=>H.name);for(let H of h.requirements){let q=this.byId.get(H.id);if(q===void 0)continue;let $=H.parent!==null?this.reqById.get(H.parent.id):void 0,Z={node:q,req:H,...$!==void 0?{parent:$}:{},children:[],...H.level!==null?{level:H.level}:{},status:H.status,kind:H.subType};if(this.requirements.push(Z),this.reqById.set(H.id,Z),$!==void 0)$.children.push(Z);else this.topRequirements.push(Z)}}file(h,H,q){let $={};for(let K of h.attrs)$[K.name]=K.value;let Z="declaredOn"in h?h.declaredOn:null,z={id:h.id,type:h.type,subType:h.subType,name:h.name,package:H,order:h.order,...q!==void 0?{parent:q}:{},path:h.path,anchor:"anchor"in h?h.anchor:"",...h.extends!==null&&!h.extends.unresolved?{extends:h.extends.id}:{},abstract:h.abstract,isArray:"isArray"in h?h.isArray:!1,...Z!==null&&!Z.unresolved?{inheritedFrom:Z.id}:{},attrs:$,view:h};if(this.byId.set(z.id,z),q!==void 0)this.kids.set(q,[...this.kids.get(q)??[],z]);return z}fileMember(h,H,q){this.file(h,H,q);for(let $ of h.memberGroups)for(let Z of $.members)this.fileMember(Z,H,h.id)}children(h){return this.kids.get(h)??[]}ownerOf(h){let H=this.byId.get(h);while(H?.parent!==void 0)H=this.byId.get(H.parent);return H?.id??h}top(h){return this.topOf.get(h)}fields(h){return this.children(h).filter((H)=>H.type===oh)}source(h){return this.children(h).find((H)=>H.type===k2)}storage(h){let H=this.source(h);if(H===void 0)return;let q=H.attrs[XH],$=H.attrs[KH],Z=H.attrs[WH]===JH||typeof q==="string",z=typeof q==="string"?q:typeof $==="string"?$:void 0;return{kind:Z?"view":"table",...z!==void 0?{name:z}:{}}}isEntity(h){return h.type===rh&&h.subType===S3}isPrompt(h){return h.type===H3&&h.subType===a3}kindOf(h){if(h.type===H3)return h.subType===a3?"prompt":"template";if(h.type!==rh)return"other";if(h.subType===S3)return"entity";if(h.subType===O2)return"value";if(h.subType===P2)return"projection";if(h.subType===A2)return"report";return"object"}storedEntities(){return this.objects.filter((h)=>this.isEntity(h)&&!h.abstract)}claims(h){let H=this.byId.get(h)?.view;if(H===void 0)return[];return H.claims.flatMap((q)=>{let $=this.reqById.get(q.requirement.id);return $===void 0?[]:[{req:$,...q.member!==""?{member:q.member}:{}}]})}generated(h){return(this.topOf.get(h)?.files??[]).flatMap((H)=>H.paths.map((q)=>({path:q,generatedBy:H.generatedBy})))}routes(h){return this.topOf.get(h)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(h){let H=[],q=($)=>{H.push($);for(let Z of $.children)q(Z)};return q(h),H}below(h){return this.subtree(h).slice(1)}rollup(h){let H={};for(let q of h.req.rollup)if(q.count>0)H[q.status]=q.count;return H}targetsOf(h){return h.req.targets.map((H)=>H.id)}linkTargets(h){return h.req.implementedBy.filter((H)=>H.resolves&&this.byId.has(H.target.id)).map((H)=>H.target.id)}featureOf(h){let H=new Map;for(let $ of this.claims(h)){let Z=$.req;while(Z.parent!==void 0)Z=Z.parent;if(Z.kind!==i)continue;H.set(Z,(H.get(Z)??0)+1)}let q;for(let $ of this.features()){let Z=H.get($)??0;if(Z>0&&(q===void 0||Z>(H.get(q)??0)))q=$}return q}features(){return this.topRequirements.filter((h)=>h.kind===i)}qualities(){return this.topRequirements.filter((h)=>h.kind===Jh)}claimStatus(h){let H=this.claims(h);if(H.length===0)return"unclaimed";for(let q of jh)if(H.some(($)=>$.req.status===q))return q;return"unclaimed"}modelEdges(){let h=[],H=new Set;for(let q of this.view.nodes){if(q.type===bh)continue;for(let $ of q.refs){let Z=this.ownerOf($.target.id),z=this.byId.get(Z);if(Z===q.id||z===void 0||z.type===bh)continue;let K=`${$.attr}\x00${q.id}\x00${Z}`;if(H.has(K))continue;H.add(K),h.push({kind:$.attr,from:q.id,to:Z,...$.via!==null?{via:$.via.id}:{}})}}return h.sort((q,$)=>GH(`${q.kind}\x00${q.from}\x00${q.to}`,`${$.kind}\x00${$.from}\x00${$.to}`))}slice(h){return this.view.slices.find((H)=>H.id===h)}}function X(h){return String(h??"").replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H])}function a(h){if(h==="")return"";return`${t3[h]??""} ${X(h)}`}function W3(h){if(h==="")return"";return`${t3[h]??""}`}function r(h){return h.level!==void 0?`L${h.level}`:'—'}var Bh="gate";function J3(h){let H=h.req.diagnostics.filter((z)=>z.source===Bh);if(H.length===0)return"";let q=H.some((z)=>z.severity==="error")?"error":"warn",$=H.map((z)=>z.code).join(", "),Z=H.length;return`${q==="error"?"✕":"!"} ${Z} gate ${q==="error"?Z===1?"error":"errors":Z===1?"warning":"warnings"}`}function _3(h){let H=h.node.attrs[Z3];return typeof H==="string"?`${X(H)}`:""}function ih(h){let H=jh.reduce((Z,z)=>Z+(h[z]??0),0),q=jh.filter((Z)=>(h[Z]??0)>0).map((Z)=>`${h[Z]} ${Z}`).join(", ");if(H===0)return'

';let $=jh.filter((Z)=>(h[Z]??0)>0).map((Z)=>``).join("");return``}function Dq(h){return`${(Math.round(h*1e4)/100).toString()}%`}function CH(h){return`
${jh.map(($)=>a($)).join("")}${h?'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 U(h,H){let q=h.split("/").length-1;return"../".repeat(q)+H}var j3="index.html",Vh="map.html",dh="requirements/features.html",ch="requirements/qualities.html",w3="matrix.html",ph="trace.html",Dh="prompts.html",Fh="api.html",sh="gaps.html",vh="model/index.html",Fq=new Set([oh,eh,F3,h3,fh,Oh,Ph]),Yq=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),Mq="WARN_REQUIREMENT_OBJECT_UNCLAIMED",wh=(h,H)=>hH?1:0,x=(h)=>typeof h==="string"?h:void 0,o=(h)=>Array.isArray(h)?h.filter((H)=>typeof H==="string"):typeof h==="string"?[h]:[];function kq(h){return h===""?"-root":h.split("::").join("/")}function Kh(h){let H=h.lastIndexOf("::");return H<0?h:h.slice(H+2)}class E3{ix;constructor(h){this.ix=h}objectPage(h){return h.path}packagePage(h){return`model/${kq(h)}/index.html`}reqPage(h){return h.req.path}reqPath(h){return h.req.address}reqLabel(h){return h.req.label}pageOf(h){let H=this.ix.byId.get(h)?.path;return H===void 0||H===""?void 0:H}implLinks(h){return h.req.implementedBy.map((H)=>({ref:H.ref,resolves:H.resolves,...H.resolves&&this.ix.byId.has(H.target.id)?{target:H.target.id}:{}}))}attrValues(h,H){return h.view.attrs.find((q)=>q.name===H)?.values??[]}refLinks(h,H){return this.attrValues(h,H).flatMap((q)=>q.link!==null&&!q.link.unresolved?[q.link]:[])}refHtml(h,H,q,$){return this.attrValues(H,q).filter((Z)=>Z.link!==null).map((Z)=>this.viewLink(h,Z.link,$?.(Z.text))).join(", ")}viewLink(h,H,q){return H.unresolved?`${X(q??Kh(H.label))} (unresolved)`:this.link(h,H.id,q)}memberAnchors(h,H){return this.ix.children(h.id).filter((q)=>!H.has(q.type)&&q.anchor!=="").map((q)=>``).join("")}kindClass(h){return`k-${this.ix.kindOf(h)}`}link(h,H,q){let $=this.pageOf(H),Z=this.ix.byId.get(this.ix.ownerOf(H));if($===void 0||Z===void 0)return`${X(q??Kh(H))} (unresolved)`;let z=this.ix.reqById.get(H),K=q??(z!==void 0?this.reqLabel(z):H===Z.id?Z.name:`${Z.name}.${H.slice(Z.id.length+1)}`);return`${X(K)}`}reqLink(h,H){return`${X(this.reqLabel(H))}`}description(h){return X(x(h.attrs[Wh])??x(h.attrs[l2])??"")}topOf(h){let H=h;while(H.parent!==void 0)H=H.parent;return H}overview(h){let H=this.ix,q=j3,$=H.storedEntities(),Z=H.objects.filter((w)=>H.isEntity(w)&&w.abstract===!0).length,z=H.templates.filter((w)=>H.isPrompt(w)),K=H.objects.filter((w)=>H.kindOf(w)==="value").length,b=H.objects.filter((w)=>H.kindOf(w)==="projection").length,J=H.objects.filter((w)=>H.kindOf(w)==="report").length,V=H.view.counts,W=[];if(W.push({n:`${$.length}`,l:`stored entities${Z>0?` (${Z} abstract base${Z===1?"":"s"})`:""}`,href:U(q,Vh)}),W.push({n:`${z.length}`,l:`declared prompt${z.length===1?"":"s"}, ${T3(K,"payload or reply type","payload and reply types")}`,href:U(q,Dh)}),H.hasRequirements())W.push({n:`${V.requirements}`,l:`requirements: ${T3(V.functional,"feature")}, ${T3(V.architectural,"quality","qualities")}`,href:U(q,dh)});else W.push({n:`${b+J}`,l:`read models: ${b} projection${b===1?"":"s"}, ${J} report${J===1?"":"s"}`,href:U(q,vh)});if(V.coverageMeasured&&V.entitiesTotal>0)W.push({n:`${V.entitiesClaimed}/${V.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:U(q,sh)});else W.push({n:`${H.packages.length}`,l:`package${H.packages.length===1?"":"s"} in the model`,href:U(q,vh)});if(H.view.sources.routes){let w=H.objects.filter((v)=>H.routes(v.id).length>0).length;W.push({n:`${w}`,l:"objects with mounted REST routes",href:U(q,Fh)})}else W.push({n:"—",l:"REST routes: none recorded by this run",href:U(q,Fh)});W.push({n:H.view.sources.files?`${V.files}`:"—",l:H.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:U(q,ph)});let y=["the effective model"];if(H.view.sources.requirements)y.push("the requirement gate's ledger");if(H.view.sources.files)y.push("the generation manifest");return{heading:X(`What ${h} does`),sourcesLine:X(lq(y)),tiles:W.map((w)=>({n:X(w.n),l:X(w.l),href:X(w.href)})),hasRequirements:H.hasRequirements(),featureCards:H.features().map((w)=>this.capCard(q,w)),qualityCards:H.qualities().map((w)=>this.capCard(q,w)),hasFeatures:H.features().length>0,hasQualities:H.qualities().length>0,packageCards:H.packages.map((w)=>this.packageCard(q,w))}}capCard(h,H){let q=this.ix.below(H).length,$=this.ix.targetsOf(H).length;return{levelHtml:r(H),linkHtml:this.reqLink(h,H),statusHtml:a(H.status),verdictHtml:J3(H),statement:X(x(H.node.attrs[uh])??""),barHtml:ih(this.ix.rollup(H)),countsLine:X(`${q} requirement${q===1?"":"s"} below · ${$} model node${$===1?"":"s"} claimed`),children:H.children.map((Z)=>({levelHtml:r(Z),linkHtml:this.reqLink(h,Z),glyphHtml:W3(Z.status)})),hasChildren:H.children.length>0}}packageCard(h,H){let q=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((b)=>b.package===H),$=new Map;for(let b of q)$.set(this.ix.kindOf(b),($.get(this.ix.kindOf(b))??0)+1);let z=["entity","value","projection","report","prompt","template","object","other"].filter((b)=>$.has(b)).map((b)=>`● ${$.get(b)} ${gq(b,$.get(b)??0)}`).join(" · "),K=q.slice(0,12);return{name:X(H===""?"(no package)":H),href:X(U(h,this.packagePage(H))),kindLineHtml:z,membersHtml:K.map((b)=>this.link(h,b.id)).join(", ")+(q.length>K.length?` +${q.length-K.length}`:"")}}map(){let h=this.ix,H=[],q=[{value:"",label:"Whole model"}];if(h.templates.some(($)=>h.isPrompt($)))q.push({value:"@prompts",label:"Prompts and their payloads"});H.push({label:"Model",options:q});for(let $ of h.topRequirements){let Z=[];for(let z of[$,...$.children]){let K=h.slice(`requirement:${z.node.id}`);if(K===void 0)continue;let b=z===$?"":" ";Z.push({value:K.id,label:`${b}${z.level!==void 0?`L${z.level} `:""}${this.reqLabel(z)} (${h.targetsOf(z).length})`})}if(Z.length>0)H.push({label:`${$.kind===i?"Feature":"Quality"}: ${this.reqLabel($)}`,options:Z})}if(h.packages.length>1)H.push({label:"Package",options:h.packages.map(($)=>({value:`package:${$}`,label:$===""?"(no package)":$}))});return{sliceGroups:H.map(($)=>({label:X($.label),options:$.options.map((Z)=>({value:X(Z.value),label:X(Z.label)}))})),hasRequirements:h.hasRequirements()}}object(h){let H=this.ix,q=this.objectPage(h),$=H.kindOf(h),Z=H.claims(h.id),z=H.storage(h.id),K=z===void 0?$==="value"?"value object: no storage":"no source":`${z.kind}${z.name!==void 0?` ${z.name}`:""}`,b=H.fields(h.id).map((d)=>this.fieldRow(q,h,d)),J=b.some((d)=>d.column!==""),V=H.children(h.id).filter((d)=>d.type===eh||d.type===F3||d.type===h3).map((d)=>this.keyRow(q,d)),W=H.children(h.id).filter((d)=>d.type===fh||d.type===Oh||d.type===Ph).map((d)=>this.reportingRow(q,d)),y=H.children(h.id).filter((d)=>d.type===M2).map((d)=>this.layoutRow(d)),w=this.unclaimedEntity(h),v=this.whyRows(q,h),l=H.top(h.id)?.referencedBy??[],k=(d)=>d===Rh||d===X3,D=[...new Set(l.filter((d)=>k(d.attr)).map((d)=>d.from.id))].sort(wh).map((d)=>this.link(q,d)),g=[...new Set(l.filter((d)=>!k(d.attr)).map((d)=>d.from.id))].sort(wh).map((d)=>this.link(q,d)),F=h.extends!==void 0?this.link(q,h.extends):"";return{id:X(h.id),name:X(h.name),kindLabel:X(`object.${h.subType}`),crumbsHtml:`Model › ${X(h.package===""?"(no package)":h.package)} › object.${X(h.subType)}${this.memberAnchors(h,Fq)}`,isAbstract:h.abstract===!0,isUnclaimed:w,isReadOnly:z?.kind==="view",kindBadge:X($),description:this.description(h),storageLine:X(K),extendsHtml:F,whyRows:v,hasWhy:v.length>0,whyEmptyHtml:this.whyEmpty(h),fields:b,hasFields:b.length>0,hasColumn:J,showClaims:this.ix.hasRequirements(),keys:V,hasKeys:V.length>0,reporting:W,hasReporting:W.length>0,layouts:y,hasLayouts:y.length>0,projection:$==="projection"?this.projectionBlock(q,h):void 0,report:$==="report"?this.reportBlock(q,h):void 0,routes:H.routes(h.id).map((d)=>({method:X(d.method),path:X(d.path)})),hasRoutes:H.routes(h.id).length>0,routesNote:!H.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:D.join(", "),referencedByHtml:g.join(", "),generated:this.generatedGroups(h.id),hasGenerated:H.generated(h.id).length>0,generatedNote:!H.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:Z.length}}unclaimedEntity(h){let H=this.ix;if(!H.isEntity(h)||h.abstract===!0)return!1;return H.top(h.id)?.unclaimed===!0}whyRows(h,H){let q=[...this.ix.claims(H.id)].sort((z,K)=>this.ix.requirements.indexOf(z.req)-this.ix.requirements.indexOf(K.req)),$=[],Z;for(let z of q){let K=this.topOf(z.req);$.push({capabilityHtml:K===Z?"":this.reqLink(h,K),reqHtml:this.reqLink(h,z.req),statement:X(x(z.req.node.attrs[uh])??""),levelHtml:r(z.req),statusHtml:a(z.req.status),onHtml:z.member!==void 0?`${X(z.member)}`:'whole object'}),Z=K}return $}whyEmpty(h){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${X(h.name)} exists.`;if(this.unclaimedEntity(h))return`No requirement claims ${X(h.name)}. The gate reports this as ${Mq}.`;return`No requirement claims ${X(h.name)}.`}fieldRow(h,H,q){let $=this.refHtml(h,q,q3),Z=q.subType===Ah?o(q.attrs[l3]):[],z=[];if(q.attrs[Y3]===!0)z.push("required");if(q.attrs[N2]===!0)z.push("filterable");if(q.attrs[f2]===!0)z.push("sortable");if(q.attrs[k3]!==void 0)z.push(`max ${String(q.attrs[k3])}`);if(q.attrs[M3]!==void 0)z.push(`default ${Xh(q.attrs[M3])}`);if(this.ix.children(q.id).some((b)=>b.type===D3))z.push("derived");let K=this.ix.claims(H.id).filter((b)=>b.member!==void 0&&b.member.split(".")[0]===q.name);return{anchor:X(q.anchor),name:X(q.name),inheritedHtml:q.inheritedFrom!==void 0?`inherited`:"",type:X(`${q.subType}${q.isArray===!0?"[]":""}`),refHtml:$!==""?` → ${$}`:"",valuesHtml:Z.length>0?`
${Z.map(X).join(" | ")}
`:"",column:X(x(q.attrs[bH])??""),flagsHtml:z.map((b)=>`${X(b)}`).join(""),claimsHtml:K.map((b)=>`${W3(b.req.status)} ${X(this.reqLabel(b.req))}`).join("
")}}keyRow(h,H){let q=o(H.attrs[g3]),$=this.refHtml(h,H,U3)||this.refHtml(h,H,s2),Z=x(H.attrs[a2]),z=x(H.attrs[p2]),K=H.type===h3?[z,Z!==void 0?`through ${Kh(Z)}`:void 0].filter((b)=>b!==void 0).join(", "):`(${q.join(", ")})`;return{anchor:X(H.anchor),kind:X(`${H.type}.${H.subType}`),name:X(H.name),inheritedHtml:H.inheritedFrom!==void 0?'inherited':"",shape:X(K),targetHtml:$!==""?`→ ${$}`:""}}reportingRow(h,H){let q=H.attrs,$=[],Z=x(q[qH]),z=this.refHtml(h,H,e2,Kh);if(Z!==void 0)$.push(`${X(Z)}(${z})`);else if(z!=="")$.push(`of ${z}`);let K=x(q[ZH]),b=x(q[zH]);if(K!==void 0&&b!==void 0)$.push(`${X(K)} ÷ ${X(b)}`);let J=x(q[hH]);if(J!==void 0)$.push(`via ${X(Kh(J))}`);let V=o(q[HH]);if(V.length>0)$.push(`grains ${V.map((y)=>`${X(y)}`).join(" ")}`);let W=x(q[$H]);if(W!==void 0)$.push(`segment ${X(W)}`);if(q[i3]!==void 0)$.push(`filter ${X(Xh(q[i3]))}`);if(q[c3]!==void 0)$.push(`default ${X(Xh(q[c3]))}`);return{anchor:X(H.anchor),kind:X(`${H.type}.${H.subType}`),name:X(H.name),definitionHtml:$.join(" · ")}}layoutRow(h){let H=[],q=o(h.attrs[jH]);if(q.length>0)H.push(`columns ${q.map((Z)=>`${X(Z)}`).join(", ")}`);let $=x(h.attrs[QH]);if($!==void 0)H.push(`sorted by ${X($)}${x(h.attrs[s3])!==void 0?` ${X(x(h.attrs[s3]))}`:""}`);if(typeof h.attrs[p3]==="number")H.push(`${h.attrs[p3]} per page`);return{kind:X(`${h.type}.${h.subType}`),name:X(h.name),detailHtml:H.join(", ")}}projectionBlock(h,H){let q=this.ix,$=[],Z=new Set;for(let z of q.fields(H.id)){if(z.extends!==void 0)Z.add(q.ownerOf(z.extends));for(let K of q.children(z.id).filter((b)=>b.type===D3)){let b=this.originDefinition(h,K);for(let J of this.refLinks(K,z3))Z.add(q.ownerOf(J.id));$.push({field:X(z.name),origin:X(`origin.${K.subType}`),definitionHtml:b})}}return{basesHtml:[...Z].filter((z)=>z!==H.id).sort(wh).map((z)=>this.link(h,z)).join(", "),origins:$,hasOrigins:$.length>0}}originDefinition(h,H){let q=H.attrs,$=(K)=>this.attrValues(H,K).map((b)=>b.link!==null&&!b.link.unresolved?this.link(h,b.link.id,Kh(b.text)):`${X(Kh(b.text))}`).join(", "),Z=[],z=x(q[E2]);if(z!==void 0)Z.push(`${X(z)}(${$(b3)})`);else if(q[b3]!==void 0)Z.push(`of ${$(b3)}`);if(q[z3]!==void 0)Z.push(`from ${$(z3)}`);if(q[A3]!==void 0)Z.push(`via ${X(Kh(String(q[A3])))}`);if(q[R3]!==void 0)Z.push(`${X(Xh(q[R3]))}`);if(q[I3]!==void 0)Z.push(`filter ${X(Xh(q[I3]))}`);return Z.join(" · ")}reportBlock(h,H){let q=H.attrs,$=this.refLinks(H,$3)[0]?.id??x(q[$3]),Z=(K,b)=>{let V=[$!==void 0?`${$}.${K}`:void 0,`${H.package===""?"":`${H.package}::`}${K}`].filter((W)=>W!==void 0).find((W)=>this.ix.byId.get(W)?.type===b||this.ix.byId.has(W)&&K.includes("."));return V!==void 0?this.link(h,V,K):`${X(K)}`},z=x(q[c2]);return{fromHtml:this.refHtml(h,H,$3),spineHtml:z!==void 0?`${X(z)}`:"",dimensionsHtml:o(q[I2]).map((K)=>Z(K,fh)).join(", "),measuresHtml:o(q[R2]).map((K)=>Z(K,Oh)).join(", "),segmentHtml:o(q[i2]).map((K)=>Z(K,Ph)).join(", "),filterHtml:q[x3]!==void 0?`${X(Xh(q[x3]))}`:""}}generatedGroups(h){let H=new Map;for(let q of this.ix.generated(h))H.set(q.generatedBy,[...H.get(q.generatedBy)??[],q.path]);return[...H.keys()].sort(wh).map((q)=>({generator:X(q),files:(H.get(q)??[]).map(($)=>X($))}))}node(h){let H=this.ix,q=this.objectPage(h),$=`${h.type}.${h.subType}`,Z=this.whyRows(q,h),z=this.attrRows(q,h),K=[...(H.top(h.id)?.referencedBy??[]).map((J)=>J.from.id),...H.claims(h.id).map((J)=>this.topOf(J.req).node.id)],b=[...new Set(K.filter((J)=>J!==h.id))].sort(wh).map((J)=>this.link(q,J));return{id:X(h.id),name:X(h.name),kindLabel:X($),crumbsHtml:`Model › ${X(h.package===""?"(no package)":h.package)} › ${X($)}`,isAbstract:h.abstract===!0,description:this.description(h),extendsHtml:h.extends!==void 0?this.link(q,h.extends):"",attrs:z,hasAttrs:z.length>0,members:H.children(h.id).map((J)=>({anchor:X(J.anchor),kind:X(`${J.type}.${J.subType}`),nameHtml:H.reqById.has(J.id)?this.link(q,J.id):X(J.name===""?`#${J.order}`:J.name),attrsHtml:this.attrRows(q,J).map((V)=>`@${V.name} ${V.valueHtml}`).join("
"),below:H.children(J.id).length})),hasMembers:H.children(h.id).length>0,whyRows:Z,hasWhy:Z.length>0,whyEmptyHtml:this.whyEmpty(h),referencedByHtml:b.join(", "),generated:this.generatedGroups(h.id),hasGenerated:H.generated(h.id).length>0,generatedNote:!H.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(h,H){return H.view.attrs.map((q)=>{let $=q.values.filter((Z)=>Z.link!==null&&!Z.link.unresolved);return{name:X(q.name),valueHtml:$.length>0&&$.length===q.values.length?$.map((Z)=>this.link(h,Z.link.id)).join(", "):`${X(Xh(q.value))}`}})}prompt(h,H){let q=this.ix,$=this.objectPage(h),Z=this.refLinks(h,Rh)[0]?.id,z=this.refLinks(h,X3)[0]?.id,K=H!==void 0?uH(H):void 0,b=Z!==void 0?q.byId.get(Z):void 0,J=z!==void 0?q.byId.get(z):void 0,V=b!==void 0?q.fields(b.id).map((D)=>({name:X(D.name),requiredHtml:D.attrs[Y3]===!0?'required':"",type:X(`${D.subType}${D.isArray===!0?"[]":""}`),refHtml:this.refHtml($,D,q3)!==""?` → ${this.refHtml($,D,q3)}`:"",usedHtml:K===void 0?'text not read':K.has(D.name)?"yes":'no'})):[],W=J!==void 0?q.fields(J.id).map((D)=>({name:X(D.name),type:X(`${D.subType}${D.isArray===!0?"[]":""}`),valuesHtml:D.subType===Ah?`
${o(D.attrs[l3]).map(X).join(" | ")}
`:""})):[],y=x(h.attrs[wH])??"",w=H!==void 0?H.replace(/\n$/,"").split(` -`).length:0,v=[K3,yH,mH,dH,VH].filter((D)=>h.attrs[D]!==void 0).map((D)=>`@${X(D)} ${X(Xh(h.attrs[D]))}`).join(""),l=q.claims(h.id),k=this.whyRows($,h);return{name:X(h.name),kindLabel:X(`template.${h.subType}`),crumbsHtml:`Prompts › ${X(h.package===""?"(no package)":h.package)} › template.${X(h.subType)}${this.memberAnchors(h,new Set)}`,isUnclaimed:q.hasClaims()&&l.length===0,description:this.description(h),attrsHtml:v,payloadHtml:b!==void 0?this.link($,b.id):"none",payloadRows:V,hasPayload:b!==void 0,replyHtml:J!==void 0?this.link($,J.id):"none",replyRows:W,hasReply:J!==void 0,textRef:X(y),textMeta:X(H!==void 0?`${y}.mustache · ${w} line${w===1?"":"s"}${x(h.attrs[K3])!==void 0?` · ${x(h.attrs[K3])}`:""}`:`${y}.mustache`),textHtml:H!==void 0?Sq(H):"",hasText:H!==void 0,generated:this.generatedGroups(h.id),hasGenerated:q.generated(h.id).length>0,generatedNote:!q.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows:k,hasWhy:k.length>0,whyEmptyHtml:q.hasRequirements()?`No requirement claims ${X(h.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 h=Dh,H=this.ix.templates.map((q)=>{let $=this.refHtml(h,q,Rh),Z=this.refHtml(h,q,X3),z=this.ix.claims(q.id);return{linkHtml:this.link(h,q.id),kind:X(`template.${q.subType}`),description:this.description(q),payloadHtml:$!==""?$:'none',replyHtml:Z!==""?Z:'none (outbound only)',claimsHtml:z.length>0?z.map((K)=>a(K.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows:H,hasRows:H.length>0}}requirements(h,H){let q=this.ix.topRequirements.filter((Z)=>Z.kind===h),$=q.length>0?`
    ${q.map((Z)=>this.treeNode(H,Z)).join("")}
`:"";return{isFeatures:h===i,featuresHref:X(U(H,dh)),qualitiesHref:X(U(H,ch)),featureCount:this.ix.requirements.filter((Z)=>Z.kind===i).length,qualityCount:this.ix.requirements.filter((Z)=>Z.kind===Jh).length,treeHtml:$,hasTree:q.length>0,emptyNote:h===i?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(h,H){let q=this.implLinks(H).map((z)=>{if(z.target!==void 0)return`${this.link(h,z.target,z.ref)}`;return H.status===Qh?`${X(z.ref)} (not yet)`:`${X(z.ref)} (dangling)`}),$=H.children.length>0?`${ih(this.ix.rollup(H))}`:"";return`
  • ${`
    ${r(H)}${this.reqLink(h,H)} ${a(H.status)}${_3(H)}${J3(H)}${$}${q.join("")}
    ${X(x(H.node.attrs[uh])??"")}
    `}${H.children.length>0?`
      ${H.children.map((z)=>this.treeNode(h,z)).join("")}
    `:""}
  • `}requirement(h){let H=this.ix,q=this.reqPage(h),$=[];for(let d=h;d!==void 0;d=d.parent)$.unshift(d);let Z=h.kind===i?{href:dh,label:"Features"}:{href:ch,label:"Qualities"},z=h.req.inLedger,K=h.req.diagnostics,b=this.implLinks(h),J=b.map((d)=>{let B=d.target!==void 0?H.byId.get(d.target):void 0;return{refHtml:B!==void 0?this.link(q,B.id,d.ref):`${X(d.ref)}`,kind:X(B!==void 0?`${B.type}.${B.subType}`:""),resolvesHtml:d.resolves?'resolves':h.status===Qh?'not yet (allowed on planned)':'dangling'}}),V=K.filter((d)=>d.source===Bh),W=K.filter((d)=>d.source!==Bh),y=K.some((d)=>Yq.has(d.code)),w=h.kind===i&&(h.level??0)>=P3,v=b.length===0?"none":b.every((d)=>d.resolves)?"yes":"no",l=H.below(h),k=H.slice(`requirement:${h.node.id}`),D=h;while(D!==void 0&&(D.level??0)>O3)D=D.parent;let g=o(h.node.attrs[t2]),F=this.description(h.node);return{crumbsHtml:`${Z.label} › ${$.map((d)=>d===h?X(this.reqLabel(d)):this.reqLink(q,d)).join(" › ")}`,levelHtml:r(h),name:X(this.reqLabel(h)),statusHtml:a(h.status),dispositionHtml:_3(h),verdictHtml:J3(h),address:X(`${h.req.qualifiedPath} · requirement.${h.kind}`),statement:X(x(h.node.attrs[uh])??""),counterexample:X(x(h.node.attrs[n2])??""),description:F,hasDescription:F!=="",linkRows:J,hasLinks:J.length>0,linksEmpty:h.level!==void 0&&h.levelh.children.length,hasBelow:h.children.length>0,belowBarHtml:ih(H.rollup(h)),children:h.children.map((d)=>({levelHtml:r(d),linkHtml:this.reqLink(q,d),statusHtml:a(d.status)})),sliceHref:k!==void 0?X(`${U(q,Vh)}?slice=${encodeURIComponent(k.id)}`):"",traceHref:D!==void 0?X(`${U(q,ph)}?start=${encodeURIComponent(D.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:v==="none"?'no links':v==="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:y?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:V.length>0?`${V.length}`:z?'none':'not read',how:V.length>0?V.map((d)=>`${X(d.code)} ${X(d.message)}`).join("
    "):z?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:z?`${W.length}`:'not read',how:W.length>0?W.map((d)=>`${X(d.code)} ${X(d.message)}`).join("
    "):z?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:w?'by generator':'not by default',how:w?"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((d)=>({what:X(d.what),verdictHtml:d.verdictHtml,howHtml:d.how})),trackedHtml:g.map((d)=>`${X(d)}`).join(" "),digest:X(h.req.digest)}}matrix(){let h=this.ix,H=w3,q=h.requirements.flatMap((b)=>this.implLinks(b).flatMap((J)=>J.target!==void 0?[h.ownerOf(J.target)]:[])),$=new Set([...h.storedEntities(),...h.templates.filter((b)=>h.isPrompt(b))].map((b)=>b.id));for(let b of q)if(h.byId.get(b)?.parent===void 0&&h.byId.get(b)?.type!==bh)$.add(b);let Z=[...$].map((b)=>h.byId.get(b)).sort((b,J)=>h.claims(J.id).length-h.claims(b.id).length||wh(b.name,J.name)||wh(b.id,J.id)),z=`${Z.map((b)=>`
    ${this.link(H,b.id)}
    `).join("")}`,K=[];for(let b of h.topRequirements){let J=h.subtree(b).filter((V)=>V.req.implementedBy.length>0);if(J.length===0)continue;K.push(`${b.kind===i?"Feature":"Quality"}: ${this.reqLink(H,b)}${Z.map(()=>'').join("")}`);for(let V of J){let W=new Set(this.implLinks(V).filter((w)=>w.target!==void 0).map((w)=>h.ownerOf(w.target))),y=this.reqPath(V).split(".").slice(1).join(".")||this.reqLabel(V);K.push(`${r(V)}${X(y)}${Z.map((w)=>W.has(w.id)?`${W3(V.status)}`:'').join("")}`)}}return{tableHtml:K.length>0?`${z}${K.join("")}
    `:"",hasRows:K.length>0,hasRequirements:h.hasRequirements()}}trace(){let h=this.ix.requirements.filter((q)=>q.level!==void 0&&q.level<=O3),H=h.length===0?this.ix.topRequirements:[];return{options:[...h,...H].map((q)=>({value:X(q.node.id),label:X(`${" ".repeat(Math.max(0,(q.level??1)-1))}${q.level!==void 0?`L${q.level} `:""}${this.reqLabel(q)}`)})),hasStarts:h.length+H.length>0,hasUsage:!1}}gaps(){let h=this.ix,H=sh,q=[],$=(z,K,b,J,V)=>{q.push({title:X(z),count:X(String(K)),source:X(b),isGate:b==="meta verify",whyHtml:J,bodyHtml:V})};if(h.view.sources.requirements){let z=(w)=>[...h.requirements.flatMap((v)=>v.req.diagnostics.filter((l)=>l.source===Bh===w).map((l)=>({req:v,d:l}))),...h.view.advisories.filter((v)=>v.path===""&&v.source===Bh===w).map((v)=>({d:v}))],K=(w,v)=>w.length===0?'
    None.
    ':`${w.map(({req:l,d:k})=>``).join("")}
    ${X(k.code)}${l!==void 0?this.reqLink(H,l):""}
    ${X(k.message)}
    `,b=z(!0);$("Gate findings",b.length,"meta verify","Printed by every run of the requirement gate.",K(b,(w)=>`chip v-${w==="error"?"error":"warn"}`));let J=z(!1);$("Authoring advisories",J.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",K(J,()=>"chip"));let V=h.storedEntities().filter((w)=>this.unclaimedEntity(w));$("Entities no requirement claims",V.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",V.length>0?V.map((w)=>this.link(H,w.id)).join(", "):'
    None.
    ');let W=(w)=>T2.includes(w.status),y=h.requirements.filter((w)=>W(w)&&w.node.attrs[Z3]===void 0&&!h.below(w).some(W));$("Undecided gaps",h.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.",Q3(y.map((w)=>`${r(w)}${this.reqLink(H,w)} ${a(w.status)}`)))}if(h.hasRequirements()){let z=h.requirements.filter((b)=>b.status===Qh&&h.below(b).some((J)=>J.status===Ih));$("Planned, with live work below",z.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.",Q3(z.map((b)=>`${r(b)}${this.reqLink(H,b)} ${a(b.status)} ${ih(h.rollup(b))}`)));let K=h.templates.filter((b)=>h.isPrompt(b)&&h.claims(b.id).length===0);$("Prompts no requirement claims",K.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",K.length>0?K.map((b)=>this.link(H,b.id)).join(", "):'
    None.
    ')}$("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let Z=h.storedEntities().flatMap((z)=>{let K=new Set(h.children(z.id).filter((b)=>b.type===eh&&b.attrs[U3]!==void 0).flatMap((b)=>o(b.attrs[g3])));return h.fields(z.id).filter((b)=>/[a-z]Id$/.test(b.name)&&!K.has(b.name))});if($("Fields that look like references but are not declared",Z.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.",Q3(Z.map((z)=>`${this.link(H,z.id)} ${X(z.subType)}`))),h.templates.length>0){let z=this.unusedPayload();$("Payload fields the prompt text never uses",z===void 0?"—":z.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.",z===void 0?'
    No prompt text was read.
    ':Q3(z.map(({p:K,f:b})=>`${this.link(H,K.id)}: ${this.link(H,b.id,b.name)}`)))}return{cards:q}}texts=new Map;unusedPayload(){let h=[],H=!1;for(let q of this.ix.templates){let $=this.texts.get(q.id),Z=this.refLinks(q,Rh)[0]?.id;if($===void 0||Z===void 0)continue;H=!0;let z=uH($);for(let K of this.ix.fields(Z))if(!z.has(K.name))h.push({p:q,f:K})}return H?h:void 0}api(){let h=this.ix,H=Fh,q=h.objects.filter((Z)=>h.routes(Z.id).length>0).map((Z)=>({linkHtml:this.link(H,Z.id),kind:X(h.kindOf(Z)),isReadOnly:h.storage(Z.id)?.kind==="view",routes:h.routes(Z.id).map((z)=>({method:X(z.method),methodClass:X(z.method.toLowerCase()),path:X(z.path)}))})),$=q.reduce((Z,z)=>Z+z.routes.length,0);return{groups:q,hasGroups:q.length>0,recorded:h.view.sources.routes,summary:X(`${$} route${$===1?"":"s"} on ${q.length} object${q.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((h)=>this.packageCard(vh,h))}}packageIndex(h){let H=this.ix,q=this.packagePage(h),$=[...H.objects,...H.templates,...H.others].filter((Z)=>Z.package===h).map((Z)=>{let z=H.storage(Z.id),K=H.claimStatus(Z.id);return{linkHtml:this.link(q,Z.id),kind:X(`${Z.type}.${Z.subType}`),abstractHtml:Z.abstract===!0?'abstract':"",storage:X(z===void 0?"":`${z.kind}${z.name!==void 0?` ${z.name}`:""}`),fieldCount:H.fields(Z.id).length,statusHtml:K==="unclaimed"?this.unclaimedEntity(Z)?'unclaimed':"":a(K),description:this.description(Z)}});return{name:X(h===""?"(no package)":h),crumbsHtml:`Model › ${X(h===""?"(no package)":h)}`,rows:$}}}function Q3(h){return h.length===0?'
    None.
    ':`
      ${h.map((H)=>`
    • ${H}
    • `).join("")}
    `}function Xh(h){return typeof h==="string"?h:JSON.stringify(h)}function lq(h){return h.length<=1?h[0]??"":`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`}function T3(h,H,q=`${H}s`){return`${h} ${h===1?H:q}`}function gq(h,H){if(H===1)return h;return h==="entity"?"entities":`${h}s`}var Uq=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function uH(h){let H=new Set;for(let q of h.matchAll(Uq))if(q[1]!=="/")H.add(q[2].split(".")[0]);return H}function Sq(h){let H="",q=0;for(let $ of h.matchAll(/\{\{[^}]*\}?\}\}/g))H+=X(h.slice(q,$.index)),H+=`${X($[0])}`,q=$.index+$[0].length;return H+X(h.slice(q))}var xq=[{key:"overview",label:"Overview",href:j3},{key:"map",label:"Model map",href:Vh},{key:"requirements",label:"Requirements",href:dh},{key:"matrix",label:"Matrix",href:w3},{key:"trace",label:"Trace",href:ph},{key:"prompts",label:"Prompts",href:Dh},{key:"api",label:"API",href:Fh},{key:"gaps",label:"Gaps",href:sh}];function Lq(h){if(h===void 0)return new Map;if(h instanceof Map)return h;return new Map(Object.entries(h))}function BH(h){let H=new n3(h.view),q=new E3(H),$=Lq(h.texts);for(let[y,w]of $)q.texts.set(y,w);let Z=(y)=>{let w=h.templates[y];if(w===void 0)throw Error(`docs-site explorer: no template ${y}`);return w},z=new Eh({card:Z("explorer-card.mustache")}),K=Z("explorer-head.mustache"),b=Z("explorer-foot.mustache"),J=CH(H.hasClaims()),V=new Map,W=(y,w,v,l,k,D=!1)=>{if(V.has(w))throw Error(`docs-site explorer: two pages map to ${w}`);let g=Z(y);V.set(w,()=>{let F=U(w,""),d={...k(),siteTitle:X(h.title),pageTitle:X(l),stamp:X(h.stamp??""),relRoot:F,assetBase:h.assetBase,cytoscapeSrc:h.cytoscapeSrc(F),graph3dSrc:h.graph3dSrc(F),needsGraph:D,pageKey:v,nav:xq.map((B)=>({label:B.label,href:U(w,B.href),on:B.key===v})),legendHtml:J};return v3({template:K+g+b,payload:d,provider:z,format:"text"})})};W("explorer-overview.html.mustache",j3,"overview","Overview",()=>q.overview(h.title)),W("explorer-map.html.mustache",Vh,"map","Model map",()=>q.map(),!0),W("explorer-requirements.html.mustache",dh,"requirements","Features",()=>q.requirements(i,dh)),W("explorer-requirements.html.mustache",ch,"requirements","Qualities",()=>q.requirements(Jh,ch)),W("explorer-matrix.html.mustache",w3,"matrix","Matrix",()=>q.matrix()),W("explorer-trace.html.mustache",ph,"trace","Trace",()=>q.trace(),!0),W("explorer-prompts.html.mustache",Dh,"prompts","Prompts",()=>q.prompts()),W("explorer-api.html.mustache",Fh,"api","API",()=>q.api()),W("explorer-gaps.html.mustache",sh,"gaps","Gaps",()=>q.gaps()),W("explorer-model.html.mustache",vh,"map","Packages",()=>q.model());for(let y of H.packages)W("explorer-package.html.mustache",q.packagePage(y),"map",y===""?"(no package)":y,()=>q.packageIndex(y));for(let y of H.objects)W("explorer-object.html.mustache",q.objectPage(y),"map",y.name,()=>q.object(y),!0);for(let y of H.templates)W("explorer-prompt.html.mustache",q.objectPage(y),"prompts",y.name,()=>q.prompt(y,$.get(y.id)));for(let y of H.others)W("explorer-node.html.mustache",q.objectPage(y),"map",y.name,()=>q.node(y));for(let y of H.requirements)W("explorer-requirement.html.mustache",q.reqPage(y),"requirements",q.reqLabel(y),()=>q.requirement(y));return{pages:V,graphData:()=>Nq(H,q)}}function Nq(h,H){let q=h.features(),$=[...h.objects,...h.templates],Z=$.map((W)=>{let y=h.featureOf(W.id),w=h.claims(W.id);return{id:W.id,name:W.name,kind:h.kindOf(W),pkg:W.package,href:H.objectPage(W),abstract:W.abstract===!0?1:0,fields:h.fields(W.id).length,claims:w.length,status:h.claimStatus(W.id),feature:y!==void 0?q.indexOf(y):-1,quality:w.length>0&&w.every((v)=>v.req.kind===Jh)?1:0,unclaimed:H.unclaimedEntity(W)?1:0,api:h.routes(W.id).map((v)=>`${v.method} ${v.path}`),gen:h.generated(W.id).length,storage:h.storage(W.id)?.kind??""}}),z=new Set($.map((W)=>W.id)),K={};for(let W of h.view.slices)K[W.id]=[...new Set(W.nodes.map((y)=>h.ownerOf(y)).filter((y)=>z.has(y)))].sort();let b=h.requirements.map((W)=>({id:W.node.id,label:H.reqLabel(W),path:H.reqPath(W),level:W.level??0,status:W.status,kind:W.kind,parent:W.parent?.node.id??"",href:H.reqPage(W),targets:h.linkTargets(W).map((y)=>h.ownerOf(y)),statement:W.req.statement,rollup:h.rollup(W),claimed:h.targetsOf(W).length})),J={};for(let W of $){let y=new Map;for(let w of h.generated(W.id))y.set(w.generatedBy,(y.get(w.generatedBy)??0)+1);if(y.size>0)J[W.id]=[...y.entries()].sort((w,v)=>w[0]v[0]?1:0)}let V=[];for(let W of $){let y=typeof W.attrs[Wh]==="string"?W.attrs[Wh]:"";V.push({t:W.name,s:`${W.type}.${W.subType}${W.package!==""?` · ${W.package}`:""}`,h:H.objectPage(W),k:`${W.name} ${W.id} ${y}`.toLowerCase()});for(let w of h.fields(W.id)){if(w.inheritedFrom!==void 0)continue;V.push({t:`${W.name}.${w.name}`,s:`field.${w.subType}`,h:H.pageOf(w.id)??H.objectPage(W),k:`${W.name}.${w.name} ${w.id}`.toLowerCase()})}}for(let W of h.others){let y=typeof W.attrs[Wh]==="string"?W.attrs[Wh]:"";V.push({t:W.name,s:`${W.type}.${W.subType}${W.package!==""?` · ${W.package}`:""}`,h:H.objectPage(W),k:`${W.name} ${W.id} ${y}`.toLowerCase()})}for(let W of h.requirements)V.push({t:H.reqLabel(W),s:`${W.level!==void 0?`L${W.level}`:"—"} ${W.kind}${W.status!==""?` · ${W.status}`:""} · ${H.reqPath(W)}`,h:H.reqPage(W),k:`${H.reqPath(W)} ${W.node.id} ${H.reqLabel(W)} ${W.req.statement}`.toLowerCase()});return{nodes:Z,edges:h.modelEdges().filter((W)=>z.has(W.from)&&z.has(W.to)).map((W)=>({s:W.from,t:W.to,k:W.kind,...W.via!==void 0?{v:fq(W.via)}:{}})),slices:K,features:q.map((W)=>({id:W.node.id,label:H.reqLabel(W)})),reqs:b,generated:J,search:V,hasClaims:h.hasClaims(),requirementType:bh}}function fq(h){let H=h.lastIndexOf(".");return H<0?h:h.slice(H+1)}function vH(h){return BH({view:h.view,title:h.title,templates:{...V3,...h.templates},texts:h.texts,...h.footer!==""&&{stamp:h.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor:vH,templates:V3};if(typeof document<"u")Oq(window);function Oq(h){let $,Z="",z={path:"",search:""},K=[],b=(C)=>{let Y=C.replace(/^#\/?/,""),j=new URL(Y===""?"index.html":Y,"http://explorer.invalid/"),Q=j.pathname.slice(1);try{Q=decodeURIComponent(Q)}catch{}return{path:Q===""?"index.html":Q,search:j.search,anchor:j.hash.slice(1)}},J=(C,Y,j="")=>`#/${C}${Y}${j!==""?`#${j}`:""}`;h.MO_APP={href:(C)=>{let Y=b(C);return J(Y.path,Y.search,Y.anchor)},search:()=>z.search,replaceQuery:(C)=>{z={path:z.path,search:C==="?"?"":C},history.replaceState(null,"",J(z.path,z.search))},listen:(C,Y)=>{document.addEventListener(C,Y),K.push(()=>document.removeEventListener(C,Y))},onLeave:(C)=>{K.push(C)}};let V=(C=h.MO_MODEL)=>{if(C===void 0)return!1;return $=vH(C),h.MO_EXPLORER=$.graphData(),Z=C.stamp,!0},y=new URLSearchParams(location.search).get("source"),w,v;if(y!==null&&y!=="")try{w=new URL(y,location.href)}catch{}let l=()=>{if(y===null||y==="")return;let C=v?.ok??!1,Y=r3(w?.href??y),j=C?`● Following the running application at ${Y}`:`● Cannot read ${Y}${v!==void 0&&v.error!==""?` (${r3(v.error)})`:""}${$!==void 0?", showing the model it last served":""}; trying again every second`,Q=document.getElementById("mo-live");if(Q===null)Q=document.createElement("div"),Q.id="mo-live",document.body.appendChild(Q);if(Q.innerHTML!==j)Q.innerHTML=j;let m=C?"live-source":"live-source down";if(Q.className!==m)Q.className=m;if(v!==void 0)Q.dataset.checked=new Date(v.at).toISOString();document.documentElement.setAttribute("data-mo-source",C?"live":"down")},k=(C,Y,j)=>{for(let Q of Array.from(C.querySelectorAll("a[href]"))){let m=Q.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(m))continue;if(m.startsWith("#")){Q.setAttribute("href",J(Y,j,m.slice(1)));continue}let G=new URL(m,"http://explorer.invalid/"+Y);Q.setAttribute("href",J(G.pathname.slice(1),G.search,G.hash.slice(1)))}},D=(C)=>{let Y=b(location.hash),j=$?.pages.get(Y.path);for(let u of K)u();K=[],z={path:Y.path,search:Y.search};let Q=j!==void 0?j():`Not found

    No such page

    ${r3(Y.path)} is not a page of this model.

    Overview

    `,m=new DOMParser().parseFromString(Q,"text/html");m.querySelectorAll("script").forEach((u)=>u.remove()),k(m,Y.path,Y.search);let G=window.scrollY;document.title=m.title;for(let u of Array.from(document.body.attributes))document.body.removeAttribute(u.name);for(let u of Array.from(m.body.attributes))document.body.setAttribute(u.name,u.value);if(document.body.replaceChildren(...Array.from(m.body.childNodes).map((u)=>document.importNode(u,!0))),j!==void 0)h.MO_THEME?.();if(C)window.scrollTo(0,G);else if(Y.anchor!=="")document.getElementById(Y.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",Y.path),l()};window.addEventListener("hashchange",()=>{let C=b(location.hash);if(C.path===z.path&&C.search===z.search){if(C.anchor!=="")document.getElementById(C.anchor)?.scrollIntoView();return}D(!1)});let g=(C,Y)=>{let j=document.createElement("script");j.src=`${C}?t=${Date.now()}`,j.onload=()=>{j.remove(),Y()},j.onerror=()=>{j.remove(),Y()},document.head.appendChild(j)},F=()=>{g("explorer-stamp.js",()=>{if(h.MO_STAMP===void 0||h.MO_STAMP===Z)return void setTimeout(F,1000);let C=h.MO_STAMP;g("explorer-model.js",()=>{if(h.MO_MODEL?.stamp===C&&V())D(!0);setTimeout(F,1000)})})},d=(C)=>{let Y="",j=async()=>{try{let Q=await fetch(C.href,{cache:"no-cache"});if(!Q.ok)throw Error(`HTTP ${Q.status}`);let m=await Q.text();if(m!==Y){let G=JSON.parse(m);if(typeof G!=="object"||G===null||!String(G.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let u=h.MO_MODEL,M=$===void 0;V({stamp:Q.headers.get("etag")??`${m.length}`,title:u?.title??C.host,footer:u?.footer??"",texts:u?.texts??{},templates:u?.templates??{},view:G}),Y=m,v={ok:!0,at:Date.now(),error:""},D(!M)}else v={ok:!0,at:Date.now(),error:""},l()}catch(Q){if(v={ok:!1,at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},$===void 0)document.body.innerHTML="

    No model yet

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

    ";l()}setTimeout(()=>void j(),1000)};j()},B=()=>{if(y!==null&&y!==""){if(w===void 0){v={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",l();return}d(w);return}if(!V())document.body.innerHTML="

    No model

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

    ";else D(!1);setTimeout(F,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",B);else B()}function r3(h){return h.replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H])}})(); + */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/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js b/server/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js index 3a52a6d4e0..dd2a04d098 100644 --- a/server/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js +++ b/server/csharp/MetaObjects.Codegen/ExplorerApp/assets/explorer-app.js @@ -11,7 +11,7 @@ * * 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. */ -(()=>{var V3={"explorer-head.mustache":` +(()=>{var explorer_templates_default={"explorer-head.mustache":` @@ -260,10 +260,10 @@ `};/*! * mustache.js - Logic-less {{mustache}} templates with JavaScript * http://github.com/janl/mustache.js - */var DH=Object.prototype.toString,Gh=Array.isArray||function(H){return DH.call(H)==="[object Array]"};function m3(h){return typeof h==="function"}function FH(h){return Gh(h)?"array":typeof h}function d3(h){return h.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function o3(h,H){return h!=null&&typeof h==="object"&&H in h}function YH(h,H){return h!=null&&typeof h!=="object"&&h.hasOwnProperty&&h.hasOwnProperty(H)}var MH=RegExp.prototype.test;function kH(h,H){return MH.call(h,H)}var lH=/\S/;function gH(h){return!kH(lH,h)}var UH={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function SH(h){return String(h).replace(/[&<>"'`=\/]/g,function(q){return UH[q]})}var xH=/\s*/,LH=/\s+/,e3=/\s*=/,NH=/\s*\}/,fH=/#|\^|\/|>|\{|&|=|!/;function OH(h,H){if(!h)return[];var q=!1,$=[],Z=[],z=[],K=!1,b=!1,J="",V=0;function W(){if(K&&!b)while(z.length)delete Z[z.pop()];else z=[];K=!1,b=!1}var y,w,v;function l(Q){if(typeof Q==="string")Q=Q.split(LH,2);if(!Gh(Q)||Q.length!==2)throw Error("Invalid tags: "+Q);y=new RegExp(d3(Q[0])+"\\s*"),w=new RegExp("\\s*"+d3(Q[1])),v=new RegExp("\\s*"+d3("}"+Q[1]))}l(H||p.tags);var k=new Mh(h),D,g,F,d,B,C;while(!k.eos()){if(D=k.pos,F=k.scanUntil(y),F)for(var Y=0,j=F.length;Y")B=[g,F,D,k.pos,J,V,q];else B=[g,F,D,k.pos];if(V++,Z.push(B),g==="#"||g==="^")$.push(B);else if(g==="/"){if(C=$.pop(),!C)throw Error('Unopened section "'+F+'" at '+D);if(C[1]!==F)throw Error('Unclosed section "'+C[1]+'" at '+D)}else if(g==="name"||g==="{"||g==="&")b=!0;else if(g==="=")l(F)}if(W(),C=$.pop(),C)throw Error('Unclosed section "'+C[1]+'" at '+k.pos);return AH(PH(Z))}function PH(h){var H=[],q,$;for(var Z=0,z=h.length;Z0?$[$.length-1][4]:H;break;default:q.push(Z)}return H}function Mh(h){this.string=h,this.tail=h,this.pos=0}Mh.prototype.eos=function(){return this.tail===""};Mh.prototype.scan=function(H){var q=this.tail.match(H);if(!q||q.index!==0)return"";var $=q[0];return this.tail=this.tail.substring($.length),this.pos+=$.length,$};Mh.prototype.scanUntil=function(H){var q=this.tail.search(H),$;switch(q){case-1:$=this.tail,this.tail="";break;case 0:$="";break;default:$=this.tail.substring(0,q),this.tail=this.tail.substring(q)}return this.pos+=$.length,$};function yh(h,H){this.view=h,this.cache={".":this.view},this.parent=H}yh.prototype.push=function(H){return new yh(H,this)};yh.prototype.lookup=function(H){var q=this.cache,$;if(q.hasOwnProperty(H))$=q[H];else{var Z=this,z,K,b,J=!1;while(Z){if(H.indexOf(".")>0){z=Z.view,K=H.split("."),b=0;while(z!=null&&b")V=this.renderPartial(b,q,$,z);else if(J==="&")V=this.unescapedValue(b,q);else if(J==="name")V=this.escapedValue(b,q,z);else if(J==="text")V=this.rawValue(b);if(V!==void 0)K+=V}return K};O.prototype.renderSection=function(H,q,$,Z,z){var K=this,b="",J=q.lookup(H[1]);function V(w){return K.render(w,q,$,z)}if(!J)return;if(Gh(J))for(var W=0,y=J.length;W0||!$))z[K]=Z+z[K];return z.join(` -`)};O.prototype.renderPartial=function(H,q,$,Z){if(!$)return;var z=this.getConfigTags(Z),K=m3($)?$(H[1]):$[H[1]];if(K!=null){var b=H[6],J=H[5],V=H[4],W=K;if(J==0&&V)W=this.indentPartial(K,V,b);var y=this.parse(W,z);return this.renderTokens(y,q,$,W,Z)}};O.prototype.unescapedValue=function(H,q){var $=q.lookup(H[1]);if($!=null)return $};O.prototype.escapedValue=function(H,q,$){var Z=this.getConfigEscape($)||p.escape,z=q.lookup(H[1]);if(z!=null)return typeof z==="number"&&Z===p.escape?String(z):Z(z)};O.prototype.rawValue=function(H){return H[1]};O.prototype.getConfigTags=function(H){if(Gh(H))return H;else if(H&&typeof H==="object")return H.tags;else return};O.prototype.getConfigEscape=function(H){if(H&&typeof H==="object"&&!Gh(H))return H.escape;else return};var p={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(h){Yh.templateCache=h},get templateCache(){return Yh.templateCache}},Yh=new O;p.clearCache=function(){return Yh.clearCache()};p.parse=function(H,q){return Yh.parse(H,q)};p.render=function(H,q,$,Z){if(typeof H!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+FH(H)+'" was given as the first argument for mustache#render(template, view, partials)');return Yh.render(H,q,$,Z)};p.escape=SH;p.Scanner=Mh;p.Context=yh;p.Writer=O;var Hh=p;var y3=(h)=>h.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),IH=/^-?[0-9]+(\.[0-9]+)?$/,H2=(h)=>/^[=+\-@\t\r]/.test(h)&&!IH.test(h)?"'"+h:h,RH=(h)=>{let H=H2(h);return/[",\n\r]/.test(H)?`"${H.replace(/"/g,'""')}"`:H},iH=(h)=>JSON.stringify(h).slice(1,-1),h2=(h)=>h,q2={text:h2,markdown:h2,html:y3,xml:y3,json:iH,csv:RH,spreadsheet:(h)=>H2(y3(h))};var $2="has";function ah(h){return"has"+cH(h)}var kh="-last";function cH(h){if(h.length===0)return h;let H=h.charAt(0);if(H===H.toUpperCase()&&H!==H.toLowerCase())return h;return H.toUpperCase()+h.slice(1)}function Z2(h){if(h===null||h===void 0)return!1;if(typeof h==="string")return h.trim().length>0;if(Array.isArray(h))return h.length>0;if(typeof h==="number"||typeof h==="boolean"||typeof h==="bigint")return;return typeof h==="object"}function z2(h,H=0){return lh(h,H,void 0)}function lh(h,H,q){if(H>32)return h;if(Array.isArray(h)){let K=h.length-1;return h.map((b,J)=>lh(b,H+1,J===K))}if(h===null||typeof h!=="object")return h;let $=Object.getPrototypeOf(h);if($!==Object.prototype&&$!==null)return sH(h,H,q);let Z=h,z={};for(let[K,b]of Object.entries(Z))z[K]=lh(b,H+1,void 0);for(let[K,b]of Object.entries(Z)){let J=ah(K);if(Object.prototype.hasOwnProperty.call(Z,J))continue;let V=Z2(b);if(V!==void 0)z[J]=V}if(q!==void 0&&!Object.prototype.hasOwnProperty.call(Z,kh))z[kh]=q;return z}function pH(h){return h.length===0?h:h.charAt(0).toLowerCase()+h.slice(1)}function sH(h,H,q){let $=new Map,Z=(K)=>{if($.has(K))return $.get(K);let b=Reflect.get(h,K,h),J=typeof b==="function"?(...V)=>lh(Reflect.apply(b,h,V),H+1,void 0):lh(b,H+1,void 0);return $.set(K,J),J},z=(K)=>{if(typeof K!=="string")return;if(K===kh)return q;if(!K.startsWith("has"))return;let b=K.slice(3);for(let J of[pH(b),b]){if(!(J in h)||ah(J)!==K)continue;let V=Reflect.get(h,J,h);if(typeof V==="function")continue;let W=Z2(V);if(W!==void 0)return W}return};return new Proxy(Object.create(null),{has:(K,b)=>(b in h)||z(b)!==void 0,get:(K,b)=>(b in h)?Z(b):z(b)})}var b2=["mustache","jinja"],gh="mustache",e="jinja";var K2=[".jinja",".j2",".jinja2"];function qh(h,H,q){let $=h.engineOf?.(H);return $!==void 0&&$!==q}function th(h,H){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${h} is not a ${H} template; a ${H} body includes only ${H} partials`}function X2(h,H,q){if(q!==void 0){if(!b2.includes(q))throw Error(`unknown template engine ${JSON.stringify(q)}; expected one of ${b2.join(", ")}`);return q}if(h!==void 0&&H!==void 0){let $=h.engineOf?.(H);if($!==void 0)return $}return"mustache"}var R="ERR_VAR_NOT_ON_PAYLOAD",Uh="ERR_PARTIAL_UNRESOLVED",G3="ERR_REQUIRED_SLOT_UNUSED";var Sh="ERR_TEMPLATE_NOT_STATIC",$h="ERR_TEMPLATE_SYNTAX",xh="ERR_TEMPLATE_ENGINE_UNSUPPORTED",t=32,aH=new Set([">"," ","\t",` -`,"\r"]);function tH(h,H){let q=`<${H}`;for(let $=h.indexOf(q);$!==-1;$=h.indexOf(q,$+1)){let Z=h[$+q.length];if(Z!==void 0&&aH.has(Z))return!0}return!1}function nH(h,H){return h.includes(``)}function nh(h,H,q){let $=[];for(let z of q?.requiredSlots??[])if(!h.has(z))$.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:z});let Z=q?.requiredTags??[];if(Z.length>0){let z=H.join(` -`);for(let K of Z)if(!tH(z,K)||!nH(z,K))$.push({code:"ERR_OUTPUT_TAG_MISSING",path:K})}return $}var _H=()=>{throw Error("the explorer app renders Mustache only")},C3=new Proxy({},{get:()=>_H});var Zh=C3;function Lh(h){return Zh.parser.parse(h)}function zh(h){return typeof h==="object"&&h!==null&&typeof h.typename==="string"}function I(h){let H=[],q=($)=>{if(Array.isArray($))$.forEach(q);else if(zh($))H.push($)};for(let $ of h.fields)q(h[$]);if(h.typename==="Set")q(h.body);return H}function Nh(h){for(let H of K2)if(h.toLowerCase().endsWith(H))return h.slice(0,-H.length);return h}function TH(h){return function(H,q){this._emit("runtime.markSafe("),h.call(this,H,q),this._emit(")")}}function EH(h){let H={getSource(q){let $=h.resolve(Nh(q));return $===void 0?null:{src:$,path:q,noCache:!0}}};return new C3.Environment(H,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function rH(h){if(h===void 0)throw Error(`render verify failed: ${R}`);return h}function W2(h,H,q,$){let Z=EH(q),z=Zh.compiler.Compiler.prototype,K=Zh.lib.escape,b=z.compileCapture,J=Zh.runtime.ensureDefined;Zh.runtime.ensureDefined=rH,Zh.lib.escape=(V)=>$(typeof V==="string"?V:String(V)),z.compileCapture=TH(b);try{return Z.renderString(h,H)}finally{Zh.lib.escape=K,z.compileCapture=b,Zh.runtime.ensureDefined=J}}var S={tag:"opaque"},oH=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),eH=new Set(["first","last","random"]),hq=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),Hq=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),qq="attribute";function J2(h,H){return{tag:"typed",fields:h.fields,isArray:h.isArray===!0,path:H}}function Q2(h,H){if(h.tag==="opaque")return S;return{tag:"typed",fields:h.isArray?h.fields:void 0,isArray:!1,path:H}}function u3(h){if(h.kind==="key")return`.${h.key}`;if(h.kind==="index")return`[${h.index}]`;return"[*]"}function j2(h,H,q){let $=[],Z=q?.provider,z=new Set,K=[h],b=(j,Q)=>{$.push({code:j,path:Q})};function J(j,Q){for(let G=Q.frames.length-1;G>=0;G--){let u=Q.frames[G].get(j);if(u!==void 0)return u}let m=Q.root.find((G)=>G.name===j);if(m!==void 0){if(Q.root===H)z.add(j);return J2(m,j)}return oH.has(j)?S:void 0}function V(j,Q,m){j.frames[j.frames.length-1].set(Q,m)}function W(j){return{...j,frames:[...j.frames,new Map]}}function y(j){let Q=[],m=j;while(m.typename==="LookupVal"){let G=m.val;if(G.typename==="Literal"&&typeof G.value==="string")Q.unshift({kind:"key",key:G.value});else if(G.typename==="Literal"&&typeof G.value==="number")Q.unshift({kind:"index",index:G.value});else Q.unshift({kind:"dynamic",node:G});m=m.target}return{base:m,segments:Q}}function w(j,Q){let{base:m,segments:G}=y(j);for(let L of G)if(L.kind==="dynamic")B(L.node,Q);let u,M;if(m.typename==="Symbol"){M=m.value;let L=M+G.map(u3).join(""),c=J(M,Q);if(c===void 0)return b(R,L),S;u=c}else u=B(m,Q),M=u.tag==="typed"?u.path:"";let s=M+G.map(u3).join("");for(let L of G){if(u.tag==="opaque")return S;if(M+=u3(L),L.kind==="key"){let c=u.isArray?void 0:u.fields?.find((mh)=>mh.name===L.key);if(c===void 0)return b(R,s),S;u=J2(c,M)}else if(u.isArray)u={tag:"typed",fields:u.fields,isArray:!1,path:M};else if(L.kind==="dynamic"&&u.fields!==void 0)return b(Sh,s),S;else u={tag:"typed",fields:u.fields,isArray:!1,path:M}}return u}function v(j,Q,m){if(j.tag==="opaque"){B(Q,m);return}if(Q.typename!=="Literal"||typeof Q.value!=="string"){B(Q,m),b(Sh,`${j.path}[*]`);return}let G=Q.value,u=j.fields;for(let M of G.split(".")){let s=u?.find((L)=>L.name===M);if(s===void 0){b(R,`${j.path}.${G}`);return}u=s.fields}}function l(j){let Q=[],m=[];for(let G of j===void 0?[]:I(j))if(G.typename==="KeywordArgs")for(let u of I(G)){let M=u.key;m.push([String(M.value),u.value])}else Q.push(G);return{positional:Q,keywords:m}}function k(j,Q){let m=String(j.name.value),{positional:G,keywords:u}=l(j.args),[M,...s]=G,L=M===void 0?S:B(M,Q);s.forEach((c,mh)=>{if(mh===Hq.get(m))v(L,c,Q);else B(c,Q)});for(let[c,mh]of u)if(c===qq)v(L,mh,Q);else B(mh,Q);if(eH.has(m))return L.tag==="typed"?Q2(L,`${L.path}|${m}`):S;if(hq.has(m))return L;return S}function D(j,Q){let m=j.name;if(m.typename==="LookupVal")B(m.target,Q);else if(m.typename==="Symbol"){let M=m.value;if(J(M,Q)===void 0)b(R,M)}else B(m,Q);let{positional:G,keywords:u}=l(j.args);return G.forEach((M)=>B(M,Q)),u.forEach(([,M])=>B(M,Q)),S}function g(j,Q){let m=W(Q);for(let G of["caller","varargs","kwargs"])V(m,G,S);for(let G of I(j.args))if(G.typename==="Symbol")V(m,G.value,S);else if(G.typename==="KeywordArgs")for(let u of I(G))B(u.value,Q),V(m,String(u.key.value),S);C(j.body,m)}function F(j,Q,m,G,u=!1){if(Q.typename!=="Literal"||typeof Q.value!=="string"){B(Q,m),b(Sh,j);return}if(Z===void 0)return;let M=Nh(Q.value);if(m.seen.includes(M)||m.seen.length>=t)return;let s=Z.resolve(M);if(s===void 0){if(!u)b(Uh,M);return}if(qh(Z,M,e)){b(xh,M);return}K.push(s);let L;try{L=Lh(s)}catch(c){b($h,`${M}: ${c.message}`);return}C(L,G(m,M))}function d(j,Q,m){if(j.typename==="Symbol")V(m,j.value,Q);else for(let G of I(j))d(G,S,m)}function B(j,Q){switch(j.typename){case"Symbol":case"LookupVal":return w(j,Q);case"Literal":case"TemplateData":return S;case"Group":{let m=I(j);if(m.length===1)return B(m[0],Q);return m.forEach((G)=>B(G,Q)),S}case"Filter":case"FilterAsync":return k(j,Q);case"FunCall":return D(j,Q);case"Caller":return g(j,Q),S;case"Is":{B(j.left,Q);let m=j.right;if(m.typename==="FunCall"){let{positional:G,keywords:u}=l(m.args);G.forEach((M)=>B(M,Q)),u.forEach(([,M])=>B(M,Q))}return S}case"Pair":{let m=j.key;if(m.typename!=="Symbol")B(m,Q);return B(j.value,Q),S}case"Capture":return C(j.body,Q),S;default:for(let m of I(j))B(m,Q);return S}}function C(j,Q){switch(j.typename){case"Root":case"NodeList":for(let m of I(j))C(m,Q);return;case"Output":for(let m of I(j))B(m,Q);return;case"If":case"IfAsync":{if(B(j.cond,Q),C(j.body,Q),zh(j.else_))C(j.else_,Q);return}case"For":case"AsyncEach":case"AsyncAll":{let m=B(j.arr,Q),G=W(Q);V(G,"loop",S);let u=j.name;if(u.typename==="Symbol"){let M=u.value;V(G,M,Q2(m,M))}else d(u,S,G);if(C(j.body,G),zh(j.else_))C(j.else_,Q);return}case"Set":{let m=j.targets.filter(zh),G=S;if(zh(j.value))G=B(j.value,Q);else if(zh(j.body))B(j.body,Q);for(let u of m){let M=u.value;V(Q,M,G.tag==="typed"&&m.length===1?{...G,path:M}:S)}return}case"Macro":V(Q,String(j.name.value),S),g(j,Q);return;case"Include":F("include",j.template,Q,(m,G)=>({...W(m),seen:[...m.seen,G]}),j.ignoreMissing===!0);return;case"Import":case"FromImport":{let m=j.withContext===!0;if(F("import",j.template,Q,(G,u)=>({frames:[new Map],root:m?H:[],seen:[...G.seen,u]})),j.typename==="Import")V(Q,String(j.target.value),S);else for(let G of I(j.names)){let u=G.typename==="Pair"?G.value:G;V(Q,String(u.value),S)}return}case"Extends":F("extends",j.template,Q,(m,G)=>({frames:[new Map],root:H,seen:[...m.seen,G]}));return;case"Block":C(j.body,Q);return;case"Switch":{B(j.expr,Q);for(let m of I(j.cases))B(m.cond,Q),C(m.body,Q);if(zh(j.default))C(j.default,Q);return}default:B(j,Q)}}let Y;try{Y=Lh(h)}catch(j){return[{code:$h,path:j.message}]}return C(Y,{frames:[new Map],root:H,seen:[]}),$.push(...nh(z,K,q)),$}function w2(h,H){if(H.includes("."))return!1;if(!H.startsWith($2))return!1;for(let q=h.length-1;q>=0;q--)for(let $ of h[q])if(H===ah($.name))return!0;return!1}function V2(h,H){return h&&H===kh}function d2(h,H){return h.find((q)=>q.name===H)}function $q(h,H){let q=H.split("."),$;for(let Z=h.length-1;Z>=0;Z--){let z=d2(h[Z],q[0]);if(z){$=z;break}}for(let Z=1;$&&ZH[0]===Zq).map((H)=>[H[1],H[2],H[3]])}function Kq(h){return Th(h).some((H)=>H[0]===bq)}function _h(h,H){if(!Kq(h))return;return H??B3(h)[0]?.[0]}function Xq(h){return Th(h).filter((H)=>H[0]===zq).map((H)=>[H[2],H[3]])}function G2(h,H){let q="",$=0;for(let[Z,z]of Xq(H))q+=h.slice($,Z),$=z;return q+h.slice($)}function Wq(h){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(h instanceof Error?h.message:"")?.[1]}function u2(h){return C2(h)}function B2(h,H,q){if(q?.engine===e)return j2(h,H,q);let $=[],Z=q?.provider,z=H,K=new Set,b=[h];function J(y,w,v,l=!1){let k=w.length===1&&w[0]===z;for(let D of y){let g=D[0],F=D[1];switch(g){case"name":case"&":case"{":{if(F===".")break;if(k)K.add(F.split(".")[0]);if(!m2(w,F)&&!w2(w,F)&&!V2(l,F))$.push({code:R,path:F});break}case"#":case"^":{let d=Array.isArray(D[4])?D[4]:[];if(F==="."){J(d,w,v,l);break}if(k)K.add(F.split(".")[0]);let B=m2(w,F);if(!B){if(V2(l,F)){J(d,w,v,l);break}if(w2(w,F)){J(d,w,v,l);break}$.push({code:R,path:F});break}let C=g==="#"&&B.fields!==void 0,Y=g==="#"&&B.isArray===!0;J(d,C?[...w,B.fields]:w,v,Y?B.fields!==void 0:l);break}case">":{if(!Z)break;if(v.includes(F)||v.length>=t)break;let d=Z.resolve(F);if(d===void 0){$.push({code:Uh,path:F});break}if(qh(Z,F,gh)){$.push({code:xh,path:F});break}let B=y2(d);if(!Array.isArray(B)){$.push(B);break}let C=_h(B,F);if(C!==void 0)$.push({code:$h,path:C});b.push(G2(d,B)),J(B,w,[...v,F],l);break}default:break}}}let V=y2(h);if(!Array.isArray(V))return[V];let W=_h(V,void 0);if(W!==void 0)$.push({code:$h,path:W});return b[0]=G2(h,V),J(V,[z],[]),$.push(...nh(K,b,q)),$}var Jq=new Set(["Include","Import","FromImport","Extends"]);function v2(h,H){if(Jq.has(h.typename)){let q=h.template;if(q.typename==="Literal"&&typeof q.value==="string")H.push({ref:Nh(q.value),optional:h.ignoreMissing===!0})}for(let q of I(h))v2(q,H)}function D2(h,H,q){let $=[];v2(Lh(h),$);for(let{ref:Z,optional:z}of $){if(q.includes(Z))throw Error(`partial cycle: ${[...q,Z].join(" -> ")}`);if(q.length>=t)throw Error(`partial depth exceeded ${t}: ${Z}`);let K=H.resolve(Z);if(K===void 0){if(z)continue;throw Error(`unresolved partial: ${Z}`)}if(qh(H,Z,e))throw Error(th(Z,e));D2(K,H,[...q,Z])}}function F2(h,H,q,$,Z){return D2(h,$,H!==void 0?[H]:[]),W2(h,typeof q==="object"&&q!==null?q:{},$,Z)}function Y2(h,H,q,$){let Z=u2(h);if(_h(Z,$)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let z=B3(Z);if(z.length===0)return h;let K="",b=0;for(let[J,V,W]of z){if(q.includes(J))throw Error(`partial cycle: ${[...q,J].join(" -> ")}`);if(q.length>=t)throw Error(`partial depth exceeded ${t}: ${J}`);let y=H.resolve(J);if(y===void 0)throw Error(`unresolved partial: ${J}`);if(qh(H,J,gh))throw Error(th(J,gh));K+=h.slice(b,V)+Y2(y,H,[...q,J],J),b=W}return K+h.slice(b)}function v3(h){let H=h.template??(h.ref!==void 0?h.provider.resolve(h.ref):void 0);if(H===void 0)throw Error(`unresolved ref: ${h.ref??"(none)"}`);let q=X2(h.provider,h.template===void 0?h.ref:void 0,h.engine);if(h.verify!==void 0){let z=B2(H,h.verify,{provider:h.provider,engine:q}).filter((K)=>K.code!==G3);if(z.length>0)throw Error(`render verify failed: ${z.map((K)=>`${K.code} (${K.path})`).join(", ")}`)}let $=q2[h.format??"text"],Z=q===e?F2(H,h.template===void 0?h.ref:void 0,h.payload,h.provider,$):jq(H,h,$);if(h.maxChars!==void 0&&Z.length>h.maxChars)throw Error(`render exceeded maxChars budget: ${Z.length} > ${h.maxChars}`);return Z}function Qq(){let h=Hh.Writer.prototype,H={escapedValue:h.escapedValue,unescapedValue:h.unescapedValue};for(let q of["escapedValue","unescapedValue"]){let $=H[q];h[q]=function(Z,z,...K){let b=String(Z[1]);if(z.lookup(b)===void 0)throw Error(`render verify failed: ${R} (${b})`);return $.call(this,Z,z,...K)}}return()=>{h.escapedValue=H.escapedValue,h.unescapedValue=H.unescapedValue}}function jq(h,H,q){let $=Y2(h,H.provider,H.ref!==void 0?[H.ref]:[]),Z=Hh.escape;Hh.escape=(b)=>q(typeof b==="string"?b:String(b));let z,K=Qq();try{z=Hh.render($,z2(H.payload),{})}finally{Hh.escape=Z,K()}return z}class Eh{map;engine;constructor(h,H={}){this.map=h;this.engine=H.engine}resolve(h){return Object.prototype.hasOwnProperty.call(this.map,h)?this.map[h]:void 0}engineOf(h){return this.resolve(h)===void 0?void 0:this.engine}}var rh="object",oh="field";var eh="identity",h3="relationship",M2="layout",k2="source",D3="origin",H3="template",F3="index",bh="requirement",fh="dimension",Oh="measure",Ph="segment";var Wh="description",l2="summary";var Ch="string";var g2="currency",Ah="enum",U2="uuid",S2="uri",x2="inet",L2="duration";var Y3="required";var M3="default",k3="maxLength";var N2="filterable",f2="sortable";var q3="objectRef";var l3="values";var g3="fields";var U3="references";var S3="entity",O2="value",P2="projection",A2="report";var $3="from",I2="dimensions",R2="measures",i2="segment",x3="filter",c2="spine";var N="eq",P="ne",n="gt",_="gte",T="lt",E="lte",A="in",L3="like",f="isNull";var R1={string:[N,P,A,L3,f],[Ah]:[N,P,A,L3,f],int:[N,P,n,_,T,E,A,f],long:[N,P,n,_,T,E,A,f],double:[N,P,n,_,T,E,A,f],float:[N,P,n,_,T,E,A,f],decimal:[N,P,n,_,T,E,A,f],[g2]:[N,P,n,_,T,E,A,f],boolean:[N,f],date:[N,P,n,_,T,E,A,f],time:[N,P,n,_,T,E,A,f],timestamp:[N,P,n,_,T,E,A,f],[U2]:[N,P,A,f],[S2]:[N,P,A,L3,f],[x2]:[N,P,A,f],[L2]:[N,P,n,_,T,E,A,f]};var wq="association",Vq="aggregation",dq="composition";var p2="cardinality",s2="objectRef",a2="through";var p1={[dq]:"cascade",[Vq]:"set-null",[wq]:"restrict"};var i="functional",Jh="architectural";var Z3="disposition",t2="trackedBy",uh="statement",n2="counterexample";var Qh="planned",Ih="live",N3="partial",f3="retired",_2=["planned","live","partial","retired"];var T2=["planned","partial"];var O3=3,P3=4;var z3="from";var E2="agg",b3="of",A3="via",I3="filter";var R3="expr";var mq=["count","sum","avg","min","max"];var r2="any",o2="all",yq="collect",E1=[...mq,r2,o2,yq];var e2="of",hH="via",HH="grains",qH="agg";var i3="filter",$H="segment",ZH="numerator",zH="denominator";var c3="default";var bH="column";var Gq="uuid",Cq="jsonb";var uq="text",Bq="varchar",vq="character varying";var Z5={[Gq]:[Ch],[Cq]:[Ch],[uq]:[Ch],[Bq]:[Ch],[vq]:[Ch]};var KH="table",XH="view";var WH="kind";var JH="view";var p3="pageSize",QH="defaultSortField",s3="defaultSortOrder";var jH="columns";var a3="prompt";var Rh="payloadRef",wH="textRef",K3="format";var X3="responseRef",VH="maxTokens";var dH="model";var mH="promptStyle";var yH="responseFormat";var jh=[Ih,N3,Qh,f3].filter((h)=>_2.includes(h)),t3={[Ih]:"●",[N3]:"◐",[Qh]:"○",[f3]:"⊘"},GH=(h,H)=>hH?1:0;class n3{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(h){this.view=h;for(let H of h.nodes){let q=this.file(H,H.package,void 0);this.topOf.set(H.id,H);for(let $ of H.memberGroups)for(let Z of $.members)this.fileMember(Z,H.package,q.id);if(H.type===rh)this.objects.push(q);else if(H.type===H3)this.templates.push(q);else if(H.type!==bh)this.others.push(q)}for(let H of this.kids.values())H.sort((q,$)=>q.order-$.order||GH(q.id,$.id));this.packages=h.packages.map((H)=>H.name);for(let H of h.requirements){let q=this.byId.get(H.id);if(q===void 0)continue;let $=H.parent!==null?this.reqById.get(H.parent.id):void 0,Z={node:q,req:H,...$!==void 0?{parent:$}:{},children:[],...H.level!==null?{level:H.level}:{},status:H.status,kind:H.subType};if(this.requirements.push(Z),this.reqById.set(H.id,Z),$!==void 0)$.children.push(Z);else this.topRequirements.push(Z)}}file(h,H,q){let $={};for(let K of h.attrs)$[K.name]=K.value;let Z="declaredOn"in h?h.declaredOn:null,z={id:h.id,type:h.type,subType:h.subType,name:h.name,package:H,order:h.order,...q!==void 0?{parent:q}:{},path:h.path,anchor:"anchor"in h?h.anchor:"",...h.extends!==null&&!h.extends.unresolved?{extends:h.extends.id}:{},abstract:h.abstract,isArray:"isArray"in h?h.isArray:!1,...Z!==null&&!Z.unresolved?{inheritedFrom:Z.id}:{},attrs:$,view:h};if(this.byId.set(z.id,z),q!==void 0)this.kids.set(q,[...this.kids.get(q)??[],z]);return z}fileMember(h,H,q){this.file(h,H,q);for(let $ of h.memberGroups)for(let Z of $.members)this.fileMember(Z,H,h.id)}children(h){return this.kids.get(h)??[]}ownerOf(h){let H=this.byId.get(h);while(H?.parent!==void 0)H=this.byId.get(H.parent);return H?.id??h}top(h){return this.topOf.get(h)}fields(h){return this.children(h).filter((H)=>H.type===oh)}source(h){return this.children(h).find((H)=>H.type===k2)}storage(h){let H=this.source(h);if(H===void 0)return;let q=H.attrs[XH],$=H.attrs[KH],Z=H.attrs[WH]===JH||typeof q==="string",z=typeof q==="string"?q:typeof $==="string"?$:void 0;return{kind:Z?"view":"table",...z!==void 0?{name:z}:{}}}isEntity(h){return h.type===rh&&h.subType===S3}isPrompt(h){return h.type===H3&&h.subType===a3}kindOf(h){if(h.type===H3)return h.subType===a3?"prompt":"template";if(h.type!==rh)return"other";if(h.subType===S3)return"entity";if(h.subType===O2)return"value";if(h.subType===P2)return"projection";if(h.subType===A2)return"report";return"object"}storedEntities(){return this.objects.filter((h)=>this.isEntity(h)&&!h.abstract)}claims(h){let H=this.byId.get(h)?.view;if(H===void 0)return[];return H.claims.flatMap((q)=>{let $=this.reqById.get(q.requirement.id);return $===void 0?[]:[{req:$,...q.member!==""?{member:q.member}:{}}]})}generated(h){return(this.topOf.get(h)?.files??[]).flatMap((H)=>H.paths.map((q)=>({path:q,generatedBy:H.generatedBy})))}routes(h){return this.topOf.get(h)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(h){let H=[],q=($)=>{H.push($);for(let Z of $.children)q(Z)};return q(h),H}below(h){return this.subtree(h).slice(1)}rollup(h){let H={};for(let q of h.req.rollup)if(q.count>0)H[q.status]=q.count;return H}targetsOf(h){return h.req.targets.map((H)=>H.id)}linkTargets(h){return h.req.implementedBy.filter((H)=>H.resolves&&this.byId.has(H.target.id)).map((H)=>H.target.id)}featureOf(h){let H=new Map;for(let $ of this.claims(h)){let Z=$.req;while(Z.parent!==void 0)Z=Z.parent;if(Z.kind!==i)continue;H.set(Z,(H.get(Z)??0)+1)}let q;for(let $ of this.features()){let Z=H.get($)??0;if(Z>0&&(q===void 0||Z>(H.get(q)??0)))q=$}return q}features(){return this.topRequirements.filter((h)=>h.kind===i)}qualities(){return this.topRequirements.filter((h)=>h.kind===Jh)}claimStatus(h){let H=this.claims(h);if(H.length===0)return"unclaimed";for(let q of jh)if(H.some(($)=>$.req.status===q))return q;return"unclaimed"}modelEdges(){let h=[],H=new Set;for(let q of this.view.nodes){if(q.type===bh)continue;for(let $ of q.refs){let Z=this.ownerOf($.target.id),z=this.byId.get(Z);if(Z===q.id||z===void 0||z.type===bh)continue;let K=`${$.attr}\x00${q.id}\x00${Z}`;if(H.has(K))continue;H.add(K),h.push({kind:$.attr,from:q.id,to:Z,...$.via!==null?{via:$.via.id}:{}})}}return h.sort((q,$)=>GH(`${q.kind}\x00${q.from}\x00${q.to}`,`${$.kind}\x00${$.from}\x00${$.to}`))}slice(h){return this.view.slices.find((H)=>H.id===h)}}function X(h){return String(h??"").replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H])}function a(h){if(h==="")return"";return`${t3[h]??""} ${X(h)}`}function W3(h){if(h==="")return"";return`${t3[h]??""}`}function r(h){return h.level!==void 0?`L${h.level}`:'—'}var Bh="gate";function J3(h){let H=h.req.diagnostics.filter((z)=>z.source===Bh);if(H.length===0)return"";let q=H.some((z)=>z.severity==="error")?"error":"warn",$=H.map((z)=>z.code).join(", "),Z=H.length;return`${q==="error"?"✕":"!"} ${Z} gate ${q==="error"?Z===1?"error":"errors":Z===1?"warning":"warnings"}`}function _3(h){let H=h.node.attrs[Z3];return typeof H==="string"?`${X(H)}`:""}function ih(h){let H=jh.reduce((Z,z)=>Z+(h[z]??0),0),q=jh.filter((Z)=>(h[Z]??0)>0).map((Z)=>`${h[Z]} ${Z}`).join(", ");if(H===0)return'
    ';let $=jh.filter((Z)=>(h[Z]??0)>0).map((Z)=>``).join("");return``}function Dq(h){return`${(Math.round(h*1e4)/100).toString()}%`}function CH(h){return`
    ${jh.map(($)=>a($)).join("")}${h?'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 U(h,H){let q=h.split("/").length-1;return"../".repeat(q)+H}var j3="index.html",Vh="map.html",dh="requirements/features.html",ch="requirements/qualities.html",w3="matrix.html",ph="trace.html",Dh="prompts.html",Fh="api.html",sh="gaps.html",vh="model/index.html",Fq=new Set([oh,eh,F3,h3,fh,Oh,Ph]),Yq=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),Mq="WARN_REQUIREMENT_OBJECT_UNCLAIMED",wh=(h,H)=>hH?1:0,x=(h)=>typeof h==="string"?h:void 0,o=(h)=>Array.isArray(h)?h.filter((H)=>typeof H==="string"):typeof h==="string"?[h]:[];function kq(h){return h===""?"-root":h.split("::").join("/")}function Kh(h){let H=h.lastIndexOf("::");return H<0?h:h.slice(H+2)}class E3{ix;constructor(h){this.ix=h}objectPage(h){return h.path}packagePage(h){return`model/${kq(h)}/index.html`}reqPage(h){return h.req.path}reqPath(h){return h.req.address}reqLabel(h){return h.req.label}pageOf(h){let H=this.ix.byId.get(h)?.path;return H===void 0||H===""?void 0:H}implLinks(h){return h.req.implementedBy.map((H)=>({ref:H.ref,resolves:H.resolves,...H.resolves&&this.ix.byId.has(H.target.id)?{target:H.target.id}:{}}))}attrValues(h,H){return h.view.attrs.find((q)=>q.name===H)?.values??[]}refLinks(h,H){return this.attrValues(h,H).flatMap((q)=>q.link!==null&&!q.link.unresolved?[q.link]:[])}refHtml(h,H,q,$){return this.attrValues(H,q).filter((Z)=>Z.link!==null).map((Z)=>this.viewLink(h,Z.link,$?.(Z.text))).join(", ")}viewLink(h,H,q){return H.unresolved?`${X(q??Kh(H.label))} (unresolved)`:this.link(h,H.id,q)}memberAnchors(h,H){return this.ix.children(h.id).filter((q)=>!H.has(q.type)&&q.anchor!=="").map((q)=>``).join("")}kindClass(h){return`k-${this.ix.kindOf(h)}`}link(h,H,q){let $=this.pageOf(H),Z=this.ix.byId.get(this.ix.ownerOf(H));if($===void 0||Z===void 0)return`${X(q??Kh(H))} (unresolved)`;let z=this.ix.reqById.get(H),K=q??(z!==void 0?this.reqLabel(z):H===Z.id?Z.name:`${Z.name}.${H.slice(Z.id.length+1)}`);return`${X(K)}`}reqLink(h,H){return`${X(this.reqLabel(H))}`}description(h){return X(x(h.attrs[Wh])??x(h.attrs[l2])??"")}topOf(h){let H=h;while(H.parent!==void 0)H=H.parent;return H}overview(h){let H=this.ix,q=j3,$=H.storedEntities(),Z=H.objects.filter((w)=>H.isEntity(w)&&w.abstract===!0).length,z=H.templates.filter((w)=>H.isPrompt(w)),K=H.objects.filter((w)=>H.kindOf(w)==="value").length,b=H.objects.filter((w)=>H.kindOf(w)==="projection").length,J=H.objects.filter((w)=>H.kindOf(w)==="report").length,V=H.view.counts,W=[];if(W.push({n:`${$.length}`,l:`stored entities${Z>0?` (${Z} abstract base${Z===1?"":"s"})`:""}`,href:U(q,Vh)}),W.push({n:`${z.length}`,l:`declared prompt${z.length===1?"":"s"}, ${T3(K,"payload or reply type","payload and reply types")}`,href:U(q,Dh)}),H.hasRequirements())W.push({n:`${V.requirements}`,l:`requirements: ${T3(V.functional,"feature")}, ${T3(V.architectural,"quality","qualities")}`,href:U(q,dh)});else W.push({n:`${b+J}`,l:`read models: ${b} projection${b===1?"":"s"}, ${J} report${J===1?"":"s"}`,href:U(q,vh)});if(V.coverageMeasured&&V.entitiesTotal>0)W.push({n:`${V.entitiesClaimed}/${V.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:U(q,sh)});else W.push({n:`${H.packages.length}`,l:`package${H.packages.length===1?"":"s"} in the model`,href:U(q,vh)});if(H.view.sources.routes){let w=H.objects.filter((v)=>H.routes(v.id).length>0).length;W.push({n:`${w}`,l:"objects with mounted REST routes",href:U(q,Fh)})}else W.push({n:"—",l:"REST routes: none recorded by this run",href:U(q,Fh)});W.push({n:H.view.sources.files?`${V.files}`:"—",l:H.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:U(q,ph)});let y=["the effective model"];if(H.view.sources.requirements)y.push("the requirement gate's ledger");if(H.view.sources.files)y.push("the generation manifest");return{heading:X(`What ${h} does`),sourcesLine:X(lq(y)),tiles:W.map((w)=>({n:X(w.n),l:X(w.l),href:X(w.href)})),hasRequirements:H.hasRequirements(),featureCards:H.features().map((w)=>this.capCard(q,w)),qualityCards:H.qualities().map((w)=>this.capCard(q,w)),hasFeatures:H.features().length>0,hasQualities:H.qualities().length>0,packageCards:H.packages.map((w)=>this.packageCard(q,w))}}capCard(h,H){let q=this.ix.below(H).length,$=this.ix.targetsOf(H).length;return{levelHtml:r(H),linkHtml:this.reqLink(h,H),statusHtml:a(H.status),verdictHtml:J3(H),statement:X(x(H.node.attrs[uh])??""),barHtml:ih(this.ix.rollup(H)),countsLine:X(`${q} requirement${q===1?"":"s"} below · ${$} model node${$===1?"":"s"} claimed`),children:H.children.map((Z)=>({levelHtml:r(Z),linkHtml:this.reqLink(h,Z),glyphHtml:W3(Z.status)})),hasChildren:H.children.length>0}}packageCard(h,H){let q=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((b)=>b.package===H),$=new Map;for(let b of q)$.set(this.ix.kindOf(b),($.get(this.ix.kindOf(b))??0)+1);let z=["entity","value","projection","report","prompt","template","object","other"].filter((b)=>$.has(b)).map((b)=>`● ${$.get(b)} ${gq(b,$.get(b)??0)}`).join(" · "),K=q.slice(0,12);return{name:X(H===""?"(no package)":H),href:X(U(h,this.packagePage(H))),kindLineHtml:z,membersHtml:K.map((b)=>this.link(h,b.id)).join(", ")+(q.length>K.length?` +${q.length-K.length}`:"")}}map(){let h=this.ix,H=[],q=[{value:"",label:"Whole model"}];if(h.templates.some(($)=>h.isPrompt($)))q.push({value:"@prompts",label:"Prompts and their payloads"});H.push({label:"Model",options:q});for(let $ of h.topRequirements){let Z=[];for(let z of[$,...$.children]){let K=h.slice(`requirement:${z.node.id}`);if(K===void 0)continue;let b=z===$?"":" ";Z.push({value:K.id,label:`${b}${z.level!==void 0?`L${z.level} `:""}${this.reqLabel(z)} (${h.targetsOf(z).length})`})}if(Z.length>0)H.push({label:`${$.kind===i?"Feature":"Quality"}: ${this.reqLabel($)}`,options:Z})}if(h.packages.length>1)H.push({label:"Package",options:h.packages.map(($)=>({value:`package:${$}`,label:$===""?"(no package)":$}))});return{sliceGroups:H.map(($)=>({label:X($.label),options:$.options.map((Z)=>({value:X(Z.value),label:X(Z.label)}))})),hasRequirements:h.hasRequirements()}}object(h){let H=this.ix,q=this.objectPage(h),$=H.kindOf(h),Z=H.claims(h.id),z=H.storage(h.id),K=z===void 0?$==="value"?"value object: no storage":"no source":`${z.kind}${z.name!==void 0?` ${z.name}`:""}`,b=H.fields(h.id).map((d)=>this.fieldRow(q,h,d)),J=b.some((d)=>d.column!==""),V=H.children(h.id).filter((d)=>d.type===eh||d.type===F3||d.type===h3).map((d)=>this.keyRow(q,d)),W=H.children(h.id).filter((d)=>d.type===fh||d.type===Oh||d.type===Ph).map((d)=>this.reportingRow(q,d)),y=H.children(h.id).filter((d)=>d.type===M2).map((d)=>this.layoutRow(d)),w=this.unclaimedEntity(h),v=this.whyRows(q,h),l=H.top(h.id)?.referencedBy??[],k=(d)=>d===Rh||d===X3,D=[...new Set(l.filter((d)=>k(d.attr)).map((d)=>d.from.id))].sort(wh).map((d)=>this.link(q,d)),g=[...new Set(l.filter((d)=>!k(d.attr)).map((d)=>d.from.id))].sort(wh).map((d)=>this.link(q,d)),F=h.extends!==void 0?this.link(q,h.extends):"";return{id:X(h.id),name:X(h.name),kindLabel:X(`object.${h.subType}`),crumbsHtml:`Model › ${X(h.package===""?"(no package)":h.package)} › object.${X(h.subType)}${this.memberAnchors(h,Fq)}`,isAbstract:h.abstract===!0,isUnclaimed:w,isReadOnly:z?.kind==="view",kindBadge:X($),description:this.description(h),storageLine:X(K),extendsHtml:F,whyRows:v,hasWhy:v.length>0,whyEmptyHtml:this.whyEmpty(h),fields:b,hasFields:b.length>0,hasColumn:J,showClaims:this.ix.hasRequirements(),keys:V,hasKeys:V.length>0,reporting:W,hasReporting:W.length>0,layouts:y,hasLayouts:y.length>0,projection:$==="projection"?this.projectionBlock(q,h):void 0,report:$==="report"?this.reportBlock(q,h):void 0,routes:H.routes(h.id).map((d)=>({method:X(d.method),path:X(d.path)})),hasRoutes:H.routes(h.id).length>0,routesNote:!H.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:D.join(", "),referencedByHtml:g.join(", "),generated:this.generatedGroups(h.id),hasGenerated:H.generated(h.id).length>0,generatedNote:!H.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:Z.length}}unclaimedEntity(h){let H=this.ix;if(!H.isEntity(h)||h.abstract===!0)return!1;return H.top(h.id)?.unclaimed===!0}whyRows(h,H){let q=[...this.ix.claims(H.id)].sort((z,K)=>this.ix.requirements.indexOf(z.req)-this.ix.requirements.indexOf(K.req)),$=[],Z;for(let z of q){let K=this.topOf(z.req);$.push({capabilityHtml:K===Z?"":this.reqLink(h,K),reqHtml:this.reqLink(h,z.req),statement:X(x(z.req.node.attrs[uh])??""),levelHtml:r(z.req),statusHtml:a(z.req.status),onHtml:z.member!==void 0?`${X(z.member)}`:'whole object'}),Z=K}return $}whyEmpty(h){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${X(h.name)} exists.`;if(this.unclaimedEntity(h))return`No requirement claims ${X(h.name)}. The gate reports this as ${Mq}.`;return`No requirement claims ${X(h.name)}.`}fieldRow(h,H,q){let $=this.refHtml(h,q,q3),Z=q.subType===Ah?o(q.attrs[l3]):[],z=[];if(q.attrs[Y3]===!0)z.push("required");if(q.attrs[N2]===!0)z.push("filterable");if(q.attrs[f2]===!0)z.push("sortable");if(q.attrs[k3]!==void 0)z.push(`max ${String(q.attrs[k3])}`);if(q.attrs[M3]!==void 0)z.push(`default ${Xh(q.attrs[M3])}`);if(this.ix.children(q.id).some((b)=>b.type===D3))z.push("derived");let K=this.ix.claims(H.id).filter((b)=>b.member!==void 0&&b.member.split(".")[0]===q.name);return{anchor:X(q.anchor),name:X(q.name),inheritedHtml:q.inheritedFrom!==void 0?`inherited`:"",type:X(`${q.subType}${q.isArray===!0?"[]":""}`),refHtml:$!==""?` → ${$}`:"",valuesHtml:Z.length>0?`
    ${Z.map(X).join(" | ")}
    `:"",column:X(x(q.attrs[bH])??""),flagsHtml:z.map((b)=>`${X(b)}`).join(""),claimsHtml:K.map((b)=>`${W3(b.req.status)} ${X(this.reqLabel(b.req))}`).join("
    ")}}keyRow(h,H){let q=o(H.attrs[g3]),$=this.refHtml(h,H,U3)||this.refHtml(h,H,s2),Z=x(H.attrs[a2]),z=x(H.attrs[p2]),K=H.type===h3?[z,Z!==void 0?`through ${Kh(Z)}`:void 0].filter((b)=>b!==void 0).join(", "):`(${q.join(", ")})`;return{anchor:X(H.anchor),kind:X(`${H.type}.${H.subType}`),name:X(H.name),inheritedHtml:H.inheritedFrom!==void 0?'inherited':"",shape:X(K),targetHtml:$!==""?`→ ${$}`:""}}reportingRow(h,H){let q=H.attrs,$=[],Z=x(q[qH]),z=this.refHtml(h,H,e2,Kh);if(Z!==void 0)$.push(`${X(Z)}(${z})`);else if(z!=="")$.push(`of ${z}`);let K=x(q[ZH]),b=x(q[zH]);if(K!==void 0&&b!==void 0)$.push(`${X(K)} ÷ ${X(b)}`);let J=x(q[hH]);if(J!==void 0)$.push(`via ${X(Kh(J))}`);let V=o(q[HH]);if(V.length>0)$.push(`grains ${V.map((y)=>`${X(y)}`).join(" ")}`);let W=x(q[$H]);if(W!==void 0)$.push(`segment ${X(W)}`);if(q[i3]!==void 0)$.push(`filter ${X(Xh(q[i3]))}`);if(q[c3]!==void 0)$.push(`default ${X(Xh(q[c3]))}`);return{anchor:X(H.anchor),kind:X(`${H.type}.${H.subType}`),name:X(H.name),definitionHtml:$.join(" · ")}}layoutRow(h){let H=[],q=o(h.attrs[jH]);if(q.length>0)H.push(`columns ${q.map((Z)=>`${X(Z)}`).join(", ")}`);let $=x(h.attrs[QH]);if($!==void 0)H.push(`sorted by ${X($)}${x(h.attrs[s3])!==void 0?` ${X(x(h.attrs[s3]))}`:""}`);if(typeof h.attrs[p3]==="number")H.push(`${h.attrs[p3]} per page`);return{kind:X(`${h.type}.${h.subType}`),name:X(h.name),detailHtml:H.join(", ")}}projectionBlock(h,H){let q=this.ix,$=[],Z=new Set;for(let z of q.fields(H.id)){if(z.extends!==void 0)Z.add(q.ownerOf(z.extends));for(let K of q.children(z.id).filter((b)=>b.type===D3)){let b=this.originDefinition(h,K);for(let J of this.refLinks(K,z3))Z.add(q.ownerOf(J.id));$.push({field:X(z.name),origin:X(`origin.${K.subType}`),definitionHtml:b})}}return{basesHtml:[...Z].filter((z)=>z!==H.id).sort(wh).map((z)=>this.link(h,z)).join(", "),origins:$,hasOrigins:$.length>0}}originDefinition(h,H){let q=H.attrs,$=(K)=>this.attrValues(H,K).map((b)=>b.link!==null&&!b.link.unresolved?this.link(h,b.link.id,Kh(b.text)):`${X(Kh(b.text))}`).join(", "),Z=[],z=x(q[E2]);if(z!==void 0)Z.push(`${X(z)}(${$(b3)})`);else if(q[b3]!==void 0)Z.push(`of ${$(b3)}`);if(q[z3]!==void 0)Z.push(`from ${$(z3)}`);if(q[A3]!==void 0)Z.push(`via ${X(Kh(String(q[A3])))}`);if(q[R3]!==void 0)Z.push(`${X(Xh(q[R3]))}`);if(q[I3]!==void 0)Z.push(`filter ${X(Xh(q[I3]))}`);return Z.join(" · ")}reportBlock(h,H){let q=H.attrs,$=this.refLinks(H,$3)[0]?.id??x(q[$3]),Z=(K,b)=>{let V=[$!==void 0?`${$}.${K}`:void 0,`${H.package===""?"":`${H.package}::`}${K}`].filter((W)=>W!==void 0).find((W)=>this.ix.byId.get(W)?.type===b||this.ix.byId.has(W)&&K.includes("."));return V!==void 0?this.link(h,V,K):`${X(K)}`},z=x(q[c2]);return{fromHtml:this.refHtml(h,H,$3),spineHtml:z!==void 0?`${X(z)}`:"",dimensionsHtml:o(q[I2]).map((K)=>Z(K,fh)).join(", "),measuresHtml:o(q[R2]).map((K)=>Z(K,Oh)).join(", "),segmentHtml:o(q[i2]).map((K)=>Z(K,Ph)).join(", "),filterHtml:q[x3]!==void 0?`${X(Xh(q[x3]))}`:""}}generatedGroups(h){let H=new Map;for(let q of this.ix.generated(h))H.set(q.generatedBy,[...H.get(q.generatedBy)??[],q.path]);return[...H.keys()].sort(wh).map((q)=>({generator:X(q),files:(H.get(q)??[]).map(($)=>X($))}))}node(h){let H=this.ix,q=this.objectPage(h),$=`${h.type}.${h.subType}`,Z=this.whyRows(q,h),z=this.attrRows(q,h),K=[...(H.top(h.id)?.referencedBy??[]).map((J)=>J.from.id),...H.claims(h.id).map((J)=>this.topOf(J.req).node.id)],b=[...new Set(K.filter((J)=>J!==h.id))].sort(wh).map((J)=>this.link(q,J));return{id:X(h.id),name:X(h.name),kindLabel:X($),crumbsHtml:`Model › ${X(h.package===""?"(no package)":h.package)} › ${X($)}`,isAbstract:h.abstract===!0,description:this.description(h),extendsHtml:h.extends!==void 0?this.link(q,h.extends):"",attrs:z,hasAttrs:z.length>0,members:H.children(h.id).map((J)=>({anchor:X(J.anchor),kind:X(`${J.type}.${J.subType}`),nameHtml:H.reqById.has(J.id)?this.link(q,J.id):X(J.name===""?`#${J.order}`:J.name),attrsHtml:this.attrRows(q,J).map((V)=>`@${V.name} ${V.valueHtml}`).join("
    "),below:H.children(J.id).length})),hasMembers:H.children(h.id).length>0,whyRows:Z,hasWhy:Z.length>0,whyEmptyHtml:this.whyEmpty(h),referencedByHtml:b.join(", "),generated:this.generatedGroups(h.id),hasGenerated:H.generated(h.id).length>0,generatedNote:!H.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(h,H){return H.view.attrs.map((q)=>{let $=q.values.filter((Z)=>Z.link!==null&&!Z.link.unresolved);return{name:X(q.name),valueHtml:$.length>0&&$.length===q.values.length?$.map((Z)=>this.link(h,Z.link.id)).join(", "):`${X(Xh(q.value))}`}})}prompt(h,H){let q=this.ix,$=this.objectPage(h),Z=this.refLinks(h,Rh)[0]?.id,z=this.refLinks(h,X3)[0]?.id,K=H!==void 0?uH(H):void 0,b=Z!==void 0?q.byId.get(Z):void 0,J=z!==void 0?q.byId.get(z):void 0,V=b!==void 0?q.fields(b.id).map((D)=>({name:X(D.name),requiredHtml:D.attrs[Y3]===!0?'required':"",type:X(`${D.subType}${D.isArray===!0?"[]":""}`),refHtml:this.refHtml($,D,q3)!==""?` → ${this.refHtml($,D,q3)}`:"",usedHtml:K===void 0?'text not read':K.has(D.name)?"yes":'no'})):[],W=J!==void 0?q.fields(J.id).map((D)=>({name:X(D.name),type:X(`${D.subType}${D.isArray===!0?"[]":""}`),valuesHtml:D.subType===Ah?`
    ${o(D.attrs[l3]).map(X).join(" | ")}
    `:""})):[],y=x(h.attrs[wH])??"",w=H!==void 0?H.replace(/\n$/,"").split(` -`).length:0,v=[K3,yH,mH,dH,VH].filter((D)=>h.attrs[D]!==void 0).map((D)=>`@${X(D)} ${X(Xh(h.attrs[D]))}`).join(""),l=q.claims(h.id),k=this.whyRows($,h);return{name:X(h.name),kindLabel:X(`template.${h.subType}`),crumbsHtml:`Prompts › ${X(h.package===""?"(no package)":h.package)} › template.${X(h.subType)}${this.memberAnchors(h,new Set)}`,isUnclaimed:q.hasClaims()&&l.length===0,description:this.description(h),attrsHtml:v,payloadHtml:b!==void 0?this.link($,b.id):"none",payloadRows:V,hasPayload:b!==void 0,replyHtml:J!==void 0?this.link($,J.id):"none",replyRows:W,hasReply:J!==void 0,textRef:X(y),textMeta:X(H!==void 0?`${y}.mustache · ${w} line${w===1?"":"s"}${x(h.attrs[K3])!==void 0?` · ${x(h.attrs[K3])}`:""}`:`${y}.mustache`),textHtml:H!==void 0?Sq(H):"",hasText:H!==void 0,generated:this.generatedGroups(h.id),hasGenerated:q.generated(h.id).length>0,generatedNote:!q.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows:k,hasWhy:k.length>0,whyEmptyHtml:q.hasRequirements()?`No requirement claims ${X(h.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 h=Dh,H=this.ix.templates.map((q)=>{let $=this.refHtml(h,q,Rh),Z=this.refHtml(h,q,X3),z=this.ix.claims(q.id);return{linkHtml:this.link(h,q.id),kind:X(`template.${q.subType}`),description:this.description(q),payloadHtml:$!==""?$:'none',replyHtml:Z!==""?Z:'none (outbound only)',claimsHtml:z.length>0?z.map((K)=>a(K.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows:H,hasRows:H.length>0}}requirements(h,H){let q=this.ix.topRequirements.filter((Z)=>Z.kind===h),$=q.length>0?`
      ${q.map((Z)=>this.treeNode(H,Z)).join("")}
    `:"";return{isFeatures:h===i,featuresHref:X(U(H,dh)),qualitiesHref:X(U(H,ch)),featureCount:this.ix.requirements.filter((Z)=>Z.kind===i).length,qualityCount:this.ix.requirements.filter((Z)=>Z.kind===Jh).length,treeHtml:$,hasTree:q.length>0,emptyNote:h===i?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(h,H){let q=this.implLinks(H).map((z)=>{if(z.target!==void 0)return`${this.link(h,z.target,z.ref)}`;return H.status===Qh?`${X(z.ref)} (not yet)`:`${X(z.ref)} (dangling)`}),$=H.children.length>0?`${ih(this.ix.rollup(H))}`:"";return`
  • ${`
    ${r(H)}${this.reqLink(h,H)} ${a(H.status)}${_3(H)}${J3(H)}${$}${q.join("")}
    ${X(x(H.node.attrs[uh])??"")}
    `}${H.children.length>0?`
      ${H.children.map((z)=>this.treeNode(h,z)).join("")}
    `:""}
  • `}requirement(h){let H=this.ix,q=this.reqPage(h),$=[];for(let d=h;d!==void 0;d=d.parent)$.unshift(d);let Z=h.kind===i?{href:dh,label:"Features"}:{href:ch,label:"Qualities"},z=h.req.inLedger,K=h.req.diagnostics,b=this.implLinks(h),J=b.map((d)=>{let B=d.target!==void 0?H.byId.get(d.target):void 0;return{refHtml:B!==void 0?this.link(q,B.id,d.ref):`${X(d.ref)}`,kind:X(B!==void 0?`${B.type}.${B.subType}`:""),resolvesHtml:d.resolves?'resolves':h.status===Qh?'not yet (allowed on planned)':'dangling'}}),V=K.filter((d)=>d.source===Bh),W=K.filter((d)=>d.source!==Bh),y=K.some((d)=>Yq.has(d.code)),w=h.kind===i&&(h.level??0)>=P3,v=b.length===0?"none":b.every((d)=>d.resolves)?"yes":"no",l=H.below(h),k=H.slice(`requirement:${h.node.id}`),D=h;while(D!==void 0&&(D.level??0)>O3)D=D.parent;let g=o(h.node.attrs[t2]),F=this.description(h.node);return{crumbsHtml:`${Z.label} › ${$.map((d)=>d===h?X(this.reqLabel(d)):this.reqLink(q,d)).join(" › ")}`,levelHtml:r(h),name:X(this.reqLabel(h)),statusHtml:a(h.status),dispositionHtml:_3(h),verdictHtml:J3(h),address:X(`${h.req.qualifiedPath} · requirement.${h.kind}`),statement:X(x(h.node.attrs[uh])??""),counterexample:X(x(h.node.attrs[n2])??""),description:F,hasDescription:F!=="",linkRows:J,hasLinks:J.length>0,linksEmpty:h.level!==void 0&&h.levelh.children.length,hasBelow:h.children.length>0,belowBarHtml:ih(H.rollup(h)),children:h.children.map((d)=>({levelHtml:r(d),linkHtml:this.reqLink(q,d),statusHtml:a(d.status)})),sliceHref:k!==void 0?X(`${U(q,Vh)}?slice=${encodeURIComponent(k.id)}`):"",traceHref:D!==void 0?X(`${U(q,ph)}?start=${encodeURIComponent(D.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:v==="none"?'no links':v==="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:y?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:V.length>0?`${V.length}`:z?'none':'not read',how:V.length>0?V.map((d)=>`${X(d.code)} ${X(d.message)}`).join("
    "):z?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:z?`${W.length}`:'not read',how:W.length>0?W.map((d)=>`${X(d.code)} ${X(d.message)}`).join("
    "):z?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:w?'by generator':'not by default',how:w?"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((d)=>({what:X(d.what),verdictHtml:d.verdictHtml,howHtml:d.how})),trackedHtml:g.map((d)=>`${X(d)}`).join(" "),digest:X(h.req.digest)}}matrix(){let h=this.ix,H=w3,q=h.requirements.flatMap((b)=>this.implLinks(b).flatMap((J)=>J.target!==void 0?[h.ownerOf(J.target)]:[])),$=new Set([...h.storedEntities(),...h.templates.filter((b)=>h.isPrompt(b))].map((b)=>b.id));for(let b of q)if(h.byId.get(b)?.parent===void 0&&h.byId.get(b)?.type!==bh)$.add(b);let Z=[...$].map((b)=>h.byId.get(b)).sort((b,J)=>h.claims(J.id).length-h.claims(b.id).length||wh(b.name,J.name)||wh(b.id,J.id)),z=`${Z.map((b)=>`
    ${this.link(H,b.id)}
    `).join("")}`,K=[];for(let b of h.topRequirements){let J=h.subtree(b).filter((V)=>V.req.implementedBy.length>0);if(J.length===0)continue;K.push(`${b.kind===i?"Feature":"Quality"}: ${this.reqLink(H,b)}${Z.map(()=>'').join("")}`);for(let V of J){let W=new Set(this.implLinks(V).filter((w)=>w.target!==void 0).map((w)=>h.ownerOf(w.target))),y=this.reqPath(V).split(".").slice(1).join(".")||this.reqLabel(V);K.push(`${r(V)}${X(y)}${Z.map((w)=>W.has(w.id)?`${W3(V.status)}`:'').join("")}`)}}return{tableHtml:K.length>0?`${z}${K.join("")}
    `:"",hasRows:K.length>0,hasRequirements:h.hasRequirements()}}trace(){let h=this.ix.requirements.filter((q)=>q.level!==void 0&&q.level<=O3),H=h.length===0?this.ix.topRequirements:[];return{options:[...h,...H].map((q)=>({value:X(q.node.id),label:X(`${" ".repeat(Math.max(0,(q.level??1)-1))}${q.level!==void 0?`L${q.level} `:""}${this.reqLabel(q)}`)})),hasStarts:h.length+H.length>0,hasUsage:!1}}gaps(){let h=this.ix,H=sh,q=[],$=(z,K,b,J,V)=>{q.push({title:X(z),count:X(String(K)),source:X(b),isGate:b==="meta verify",whyHtml:J,bodyHtml:V})};if(h.view.sources.requirements){let z=(w)=>[...h.requirements.flatMap((v)=>v.req.diagnostics.filter((l)=>l.source===Bh===w).map((l)=>({req:v,d:l}))),...h.view.advisories.filter((v)=>v.path===""&&v.source===Bh===w).map((v)=>({d:v}))],K=(w,v)=>w.length===0?'
    None.
    ':`${w.map(({req:l,d:k})=>``).join("")}
    ${X(k.code)}${l!==void 0?this.reqLink(H,l):""}
    ${X(k.message)}
    `,b=z(!0);$("Gate findings",b.length,"meta verify","Printed by every run of the requirement gate.",K(b,(w)=>`chip v-${w==="error"?"error":"warn"}`));let J=z(!1);$("Authoring advisories",J.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",K(J,()=>"chip"));let V=h.storedEntities().filter((w)=>this.unclaimedEntity(w));$("Entities no requirement claims",V.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",V.length>0?V.map((w)=>this.link(H,w.id)).join(", "):'
    None.
    ');let W=(w)=>T2.includes(w.status),y=h.requirements.filter((w)=>W(w)&&w.node.attrs[Z3]===void 0&&!h.below(w).some(W));$("Undecided gaps",h.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.",Q3(y.map((w)=>`${r(w)}${this.reqLink(H,w)} ${a(w.status)}`)))}if(h.hasRequirements()){let z=h.requirements.filter((b)=>b.status===Qh&&h.below(b).some((J)=>J.status===Ih));$("Planned, with live work below",z.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.",Q3(z.map((b)=>`${r(b)}${this.reqLink(H,b)} ${a(b.status)} ${ih(h.rollup(b))}`)));let K=h.templates.filter((b)=>h.isPrompt(b)&&h.claims(b.id).length===0);$("Prompts no requirement claims",K.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",K.length>0?K.map((b)=>this.link(H,b.id)).join(", "):'
    None.
    ')}$("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let Z=h.storedEntities().flatMap((z)=>{let K=new Set(h.children(z.id).filter((b)=>b.type===eh&&b.attrs[U3]!==void 0).flatMap((b)=>o(b.attrs[g3])));return h.fields(z.id).filter((b)=>/[a-z]Id$/.test(b.name)&&!K.has(b.name))});if($("Fields that look like references but are not declared",Z.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.",Q3(Z.map((z)=>`${this.link(H,z.id)} ${X(z.subType)}`))),h.templates.length>0){let z=this.unusedPayload();$("Payload fields the prompt text never uses",z===void 0?"—":z.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.",z===void 0?'
    No prompt text was read.
    ':Q3(z.map(({p:K,f:b})=>`${this.link(H,K.id)}: ${this.link(H,b.id,b.name)}`)))}return{cards:q}}texts=new Map;unusedPayload(){let h=[],H=!1;for(let q of this.ix.templates){let $=this.texts.get(q.id),Z=this.refLinks(q,Rh)[0]?.id;if($===void 0||Z===void 0)continue;H=!0;let z=uH($);for(let K of this.ix.fields(Z))if(!z.has(K.name))h.push({p:q,f:K})}return H?h:void 0}api(){let h=this.ix,H=Fh,q=h.objects.filter((Z)=>h.routes(Z.id).length>0).map((Z)=>({linkHtml:this.link(H,Z.id),kind:X(h.kindOf(Z)),isReadOnly:h.storage(Z.id)?.kind==="view",routes:h.routes(Z.id).map((z)=>({method:X(z.method),methodClass:X(z.method.toLowerCase()),path:X(z.path)}))})),$=q.reduce((Z,z)=>Z+z.routes.length,0);return{groups:q,hasGroups:q.length>0,recorded:h.view.sources.routes,summary:X(`${$} route${$===1?"":"s"} on ${q.length} object${q.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((h)=>this.packageCard(vh,h))}}packageIndex(h){let H=this.ix,q=this.packagePage(h),$=[...H.objects,...H.templates,...H.others].filter((Z)=>Z.package===h).map((Z)=>{let z=H.storage(Z.id),K=H.claimStatus(Z.id);return{linkHtml:this.link(q,Z.id),kind:X(`${Z.type}.${Z.subType}`),abstractHtml:Z.abstract===!0?'abstract':"",storage:X(z===void 0?"":`${z.kind}${z.name!==void 0?` ${z.name}`:""}`),fieldCount:H.fields(Z.id).length,statusHtml:K==="unclaimed"?this.unclaimedEntity(Z)?'unclaimed':"":a(K),description:this.description(Z)}});return{name:X(h===""?"(no package)":h),crumbsHtml:`Model › ${X(h===""?"(no package)":h)}`,rows:$}}}function Q3(h){return h.length===0?'
    None.
    ':`
      ${h.map((H)=>`
    • ${H}
    • `).join("")}
    `}function Xh(h){return typeof h==="string"?h:JSON.stringify(h)}function lq(h){return h.length<=1?h[0]??"":`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`}function T3(h,H,q=`${H}s`){return`${h} ${h===1?H:q}`}function gq(h,H){if(H===1)return h;return h==="entity"?"entities":`${h}s`}var Uq=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function uH(h){let H=new Set;for(let q of h.matchAll(Uq))if(q[1]!=="/")H.add(q[2].split(".")[0]);return H}function Sq(h){let H="",q=0;for(let $ of h.matchAll(/\{\{[^}]*\}?\}\}/g))H+=X(h.slice(q,$.index)),H+=`${X($[0])}`,q=$.index+$[0].length;return H+X(h.slice(q))}var xq=[{key:"overview",label:"Overview",href:j3},{key:"map",label:"Model map",href:Vh},{key:"requirements",label:"Requirements",href:dh},{key:"matrix",label:"Matrix",href:w3},{key:"trace",label:"Trace",href:ph},{key:"prompts",label:"Prompts",href:Dh},{key:"api",label:"API",href:Fh},{key:"gaps",label:"Gaps",href:sh}];function Lq(h){if(h===void 0)return new Map;if(h instanceof Map)return h;return new Map(Object.entries(h))}function BH(h){let H=new n3(h.view),q=new E3(H),$=Lq(h.texts);for(let[y,w]of $)q.texts.set(y,w);let Z=(y)=>{let w=h.templates[y];if(w===void 0)throw Error(`docs-site explorer: no template ${y}`);return w},z=new Eh({card:Z("explorer-card.mustache")}),K=Z("explorer-head.mustache"),b=Z("explorer-foot.mustache"),J=CH(H.hasClaims()),V=new Map,W=(y,w,v,l,k,D=!1)=>{if(V.has(w))throw Error(`docs-site explorer: two pages map to ${w}`);let g=Z(y);V.set(w,()=>{let F=U(w,""),d={...k(),siteTitle:X(h.title),pageTitle:X(l),stamp:X(h.stamp??""),relRoot:F,assetBase:h.assetBase,cytoscapeSrc:h.cytoscapeSrc(F),graph3dSrc:h.graph3dSrc(F),needsGraph:D,pageKey:v,nav:xq.map((B)=>({label:B.label,href:U(w,B.href),on:B.key===v})),legendHtml:J};return v3({template:K+g+b,payload:d,provider:z,format:"text"})})};W("explorer-overview.html.mustache",j3,"overview","Overview",()=>q.overview(h.title)),W("explorer-map.html.mustache",Vh,"map","Model map",()=>q.map(),!0),W("explorer-requirements.html.mustache",dh,"requirements","Features",()=>q.requirements(i,dh)),W("explorer-requirements.html.mustache",ch,"requirements","Qualities",()=>q.requirements(Jh,ch)),W("explorer-matrix.html.mustache",w3,"matrix","Matrix",()=>q.matrix()),W("explorer-trace.html.mustache",ph,"trace","Trace",()=>q.trace(),!0),W("explorer-prompts.html.mustache",Dh,"prompts","Prompts",()=>q.prompts()),W("explorer-api.html.mustache",Fh,"api","API",()=>q.api()),W("explorer-gaps.html.mustache",sh,"gaps","Gaps",()=>q.gaps()),W("explorer-model.html.mustache",vh,"map","Packages",()=>q.model());for(let y of H.packages)W("explorer-package.html.mustache",q.packagePage(y),"map",y===""?"(no package)":y,()=>q.packageIndex(y));for(let y of H.objects)W("explorer-object.html.mustache",q.objectPage(y),"map",y.name,()=>q.object(y),!0);for(let y of H.templates)W("explorer-prompt.html.mustache",q.objectPage(y),"prompts",y.name,()=>q.prompt(y,$.get(y.id)));for(let y of H.others)W("explorer-node.html.mustache",q.objectPage(y),"map",y.name,()=>q.node(y));for(let y of H.requirements)W("explorer-requirement.html.mustache",q.reqPage(y),"requirements",q.reqLabel(y),()=>q.requirement(y));return{pages:V,graphData:()=>Nq(H,q)}}function Nq(h,H){let q=h.features(),$=[...h.objects,...h.templates],Z=$.map((W)=>{let y=h.featureOf(W.id),w=h.claims(W.id);return{id:W.id,name:W.name,kind:h.kindOf(W),pkg:W.package,href:H.objectPage(W),abstract:W.abstract===!0?1:0,fields:h.fields(W.id).length,claims:w.length,status:h.claimStatus(W.id),feature:y!==void 0?q.indexOf(y):-1,quality:w.length>0&&w.every((v)=>v.req.kind===Jh)?1:0,unclaimed:H.unclaimedEntity(W)?1:0,api:h.routes(W.id).map((v)=>`${v.method} ${v.path}`),gen:h.generated(W.id).length,storage:h.storage(W.id)?.kind??""}}),z=new Set($.map((W)=>W.id)),K={};for(let W of h.view.slices)K[W.id]=[...new Set(W.nodes.map((y)=>h.ownerOf(y)).filter((y)=>z.has(y)))].sort();let b=h.requirements.map((W)=>({id:W.node.id,label:H.reqLabel(W),path:H.reqPath(W),level:W.level??0,status:W.status,kind:W.kind,parent:W.parent?.node.id??"",href:H.reqPage(W),targets:h.linkTargets(W).map((y)=>h.ownerOf(y)),statement:W.req.statement,rollup:h.rollup(W),claimed:h.targetsOf(W).length})),J={};for(let W of $){let y=new Map;for(let w of h.generated(W.id))y.set(w.generatedBy,(y.get(w.generatedBy)??0)+1);if(y.size>0)J[W.id]=[...y.entries()].sort((w,v)=>w[0]v[0]?1:0)}let V=[];for(let W of $){let y=typeof W.attrs[Wh]==="string"?W.attrs[Wh]:"";V.push({t:W.name,s:`${W.type}.${W.subType}${W.package!==""?` · ${W.package}`:""}`,h:H.objectPage(W),k:`${W.name} ${W.id} ${y}`.toLowerCase()});for(let w of h.fields(W.id)){if(w.inheritedFrom!==void 0)continue;V.push({t:`${W.name}.${w.name}`,s:`field.${w.subType}`,h:H.pageOf(w.id)??H.objectPage(W),k:`${W.name}.${w.name} ${w.id}`.toLowerCase()})}}for(let W of h.others){let y=typeof W.attrs[Wh]==="string"?W.attrs[Wh]:"";V.push({t:W.name,s:`${W.type}.${W.subType}${W.package!==""?` · ${W.package}`:""}`,h:H.objectPage(W),k:`${W.name} ${W.id} ${y}`.toLowerCase()})}for(let W of h.requirements)V.push({t:H.reqLabel(W),s:`${W.level!==void 0?`L${W.level}`:"—"} ${W.kind}${W.status!==""?` · ${W.status}`:""} · ${H.reqPath(W)}`,h:H.reqPage(W),k:`${H.reqPath(W)} ${W.node.id} ${H.reqLabel(W)} ${W.req.statement}`.toLowerCase()});return{nodes:Z,edges:h.modelEdges().filter((W)=>z.has(W.from)&&z.has(W.to)).map((W)=>({s:W.from,t:W.to,k:W.kind,...W.via!==void 0?{v:fq(W.via)}:{}})),slices:K,features:q.map((W)=>({id:W.node.id,label:H.reqLabel(W)})),reqs:b,generated:J,search:V,hasClaims:h.hasClaims(),requirementType:bh}}function fq(h){let H=h.lastIndexOf(".");return H<0?h:h.slice(H+1)}function vH(h){return BH({view:h.view,title:h.title,templates:{...V3,...h.templates},texts:h.texts,...h.footer!==""&&{stamp:h.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor:vH,templates:V3};if(typeof document<"u")Oq(window);function Oq(h){let $,Z="",z={path:"",search:""},K=[],b=(C)=>{let Y=C.replace(/^#\/?/,""),j=new URL(Y===""?"index.html":Y,"http://explorer.invalid/"),Q=j.pathname.slice(1);try{Q=decodeURIComponent(Q)}catch{}return{path:Q===""?"index.html":Q,search:j.search,anchor:j.hash.slice(1)}},J=(C,Y,j="")=>`#/${C}${Y}${j!==""?`#${j}`:""}`;h.MO_APP={href:(C)=>{let Y=b(C);return J(Y.path,Y.search,Y.anchor)},search:()=>z.search,replaceQuery:(C)=>{z={path:z.path,search:C==="?"?"":C},history.replaceState(null,"",J(z.path,z.search))},listen:(C,Y)=>{document.addEventListener(C,Y),K.push(()=>document.removeEventListener(C,Y))},onLeave:(C)=>{K.push(C)}};let V=(C=h.MO_MODEL)=>{if(C===void 0)return!1;return $=vH(C),h.MO_EXPLORER=$.graphData(),Z=C.stamp,!0},y=new URLSearchParams(location.search).get("source"),w,v;if(y!==null&&y!=="")try{w=new URL(y,location.href)}catch{}let l=()=>{if(y===null||y==="")return;let C=v?.ok??!1,Y=r3(w?.href??y),j=C?`● Following the running application at ${Y}`:`● Cannot read ${Y}${v!==void 0&&v.error!==""?` (${r3(v.error)})`:""}${$!==void 0?", showing the model it last served":""}; trying again every second`,Q=document.getElementById("mo-live");if(Q===null)Q=document.createElement("div"),Q.id="mo-live",document.body.appendChild(Q);if(Q.innerHTML!==j)Q.innerHTML=j;let m=C?"live-source":"live-source down";if(Q.className!==m)Q.className=m;if(v!==void 0)Q.dataset.checked=new Date(v.at).toISOString();document.documentElement.setAttribute("data-mo-source",C?"live":"down")},k=(C,Y,j)=>{for(let Q of Array.from(C.querySelectorAll("a[href]"))){let m=Q.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(m))continue;if(m.startsWith("#")){Q.setAttribute("href",J(Y,j,m.slice(1)));continue}let G=new URL(m,"http://explorer.invalid/"+Y);Q.setAttribute("href",J(G.pathname.slice(1),G.search,G.hash.slice(1)))}},D=(C)=>{let Y=b(location.hash),j=$?.pages.get(Y.path);for(let u of K)u();K=[],z={path:Y.path,search:Y.search};let Q=j!==void 0?j():`Not found

    No such page

    ${r3(Y.path)} is not a page of this model.

    Overview

    `,m=new DOMParser().parseFromString(Q,"text/html");m.querySelectorAll("script").forEach((u)=>u.remove()),k(m,Y.path,Y.search);let G=window.scrollY;document.title=m.title;for(let u of Array.from(document.body.attributes))document.body.removeAttribute(u.name);for(let u of Array.from(m.body.attributes))document.body.setAttribute(u.name,u.value);if(document.body.replaceChildren(...Array.from(m.body.childNodes).map((u)=>document.importNode(u,!0))),j!==void 0)h.MO_THEME?.();if(C)window.scrollTo(0,G);else if(Y.anchor!=="")document.getElementById(Y.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",Y.path),l()};window.addEventListener("hashchange",()=>{let C=b(location.hash);if(C.path===z.path&&C.search===z.search){if(C.anchor!=="")document.getElementById(C.anchor)?.scrollIntoView();return}D(!1)});let g=(C,Y)=>{let j=document.createElement("script");j.src=`${C}?t=${Date.now()}`,j.onload=()=>{j.remove(),Y()},j.onerror=()=>{j.remove(),Y()},document.head.appendChild(j)},F=()=>{g("explorer-stamp.js",()=>{if(h.MO_STAMP===void 0||h.MO_STAMP===Z)return void setTimeout(F,1000);let C=h.MO_STAMP;g("explorer-model.js",()=>{if(h.MO_MODEL?.stamp===C&&V())D(!0);setTimeout(F,1000)})})},d=(C)=>{let Y="",j=async()=>{try{let Q=await fetch(C.href,{cache:"no-cache"});if(!Q.ok)throw Error(`HTTP ${Q.status}`);let m=await Q.text();if(m!==Y){let G=JSON.parse(m);if(typeof G!=="object"||G===null||!String(G.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let u=h.MO_MODEL,M=$===void 0;V({stamp:Q.headers.get("etag")??`${m.length}`,title:u?.title??C.host,footer:u?.footer??"",texts:u?.texts??{},templates:u?.templates??{},view:G}),Y=m,v={ok:!0,at:Date.now(),error:""},D(!M)}else v={ok:!0,at:Date.now(),error:""},l()}catch(Q){if(v={ok:!1,at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},$===void 0)document.body.innerHTML="

    No model yet

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

    ";l()}setTimeout(()=>void j(),1000)};j()},B=()=>{if(y!==null&&y!==""){if(w===void 0){v={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",l();return}d(w);return}if(!V())document.body.innerHTML="

    No model

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

    ";else D(!1);setTimeout(F,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",B);else B()}function r3(h){return h.replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H])}})(); + */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/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js b/server/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js index 3a52a6d4e0..dd2a04d098 100644 --- a/server/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js +++ b/server/java/codegen-base/src/main/resources/metaobjects/explorer-app/assets/explorer-app.js @@ -11,7 +11,7 @@ * * 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. */ -(()=>{var V3={"explorer-head.mustache":` +(()=>{var explorer_templates_default={"explorer-head.mustache":` @@ -260,10 +260,10 @@ `};/*! * mustache.js - Logic-less {{mustache}} templates with JavaScript * http://github.com/janl/mustache.js - */var DH=Object.prototype.toString,Gh=Array.isArray||function(H){return DH.call(H)==="[object Array]"};function m3(h){return typeof h==="function"}function FH(h){return Gh(h)?"array":typeof h}function d3(h){return h.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function o3(h,H){return h!=null&&typeof h==="object"&&H in h}function YH(h,H){return h!=null&&typeof h!=="object"&&h.hasOwnProperty&&h.hasOwnProperty(H)}var MH=RegExp.prototype.test;function kH(h,H){return MH.call(h,H)}var lH=/\S/;function gH(h){return!kH(lH,h)}var UH={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function SH(h){return String(h).replace(/[&<>"'`=\/]/g,function(q){return UH[q]})}var xH=/\s*/,LH=/\s+/,e3=/\s*=/,NH=/\s*\}/,fH=/#|\^|\/|>|\{|&|=|!/;function OH(h,H){if(!h)return[];var q=!1,$=[],Z=[],z=[],K=!1,b=!1,J="",V=0;function W(){if(K&&!b)while(z.length)delete Z[z.pop()];else z=[];K=!1,b=!1}var y,w,v;function l(Q){if(typeof Q==="string")Q=Q.split(LH,2);if(!Gh(Q)||Q.length!==2)throw Error("Invalid tags: "+Q);y=new RegExp(d3(Q[0])+"\\s*"),w=new RegExp("\\s*"+d3(Q[1])),v=new RegExp("\\s*"+d3("}"+Q[1]))}l(H||p.tags);var k=new Mh(h),D,g,F,d,B,C;while(!k.eos()){if(D=k.pos,F=k.scanUntil(y),F)for(var Y=0,j=F.length;Y")B=[g,F,D,k.pos,J,V,q];else B=[g,F,D,k.pos];if(V++,Z.push(B),g==="#"||g==="^")$.push(B);else if(g==="/"){if(C=$.pop(),!C)throw Error('Unopened section "'+F+'" at '+D);if(C[1]!==F)throw Error('Unclosed section "'+C[1]+'" at '+D)}else if(g==="name"||g==="{"||g==="&")b=!0;else if(g==="=")l(F)}if(W(),C=$.pop(),C)throw Error('Unclosed section "'+C[1]+'" at '+k.pos);return AH(PH(Z))}function PH(h){var H=[],q,$;for(var Z=0,z=h.length;Z0?$[$.length-1][4]:H;break;default:q.push(Z)}return H}function Mh(h){this.string=h,this.tail=h,this.pos=0}Mh.prototype.eos=function(){return this.tail===""};Mh.prototype.scan=function(H){var q=this.tail.match(H);if(!q||q.index!==0)return"";var $=q[0];return this.tail=this.tail.substring($.length),this.pos+=$.length,$};Mh.prototype.scanUntil=function(H){var q=this.tail.search(H),$;switch(q){case-1:$=this.tail,this.tail="";break;case 0:$="";break;default:$=this.tail.substring(0,q),this.tail=this.tail.substring(q)}return this.pos+=$.length,$};function yh(h,H){this.view=h,this.cache={".":this.view},this.parent=H}yh.prototype.push=function(H){return new yh(H,this)};yh.prototype.lookup=function(H){var q=this.cache,$;if(q.hasOwnProperty(H))$=q[H];else{var Z=this,z,K,b,J=!1;while(Z){if(H.indexOf(".")>0){z=Z.view,K=H.split("."),b=0;while(z!=null&&b")V=this.renderPartial(b,q,$,z);else if(J==="&")V=this.unescapedValue(b,q);else if(J==="name")V=this.escapedValue(b,q,z);else if(J==="text")V=this.rawValue(b);if(V!==void 0)K+=V}return K};O.prototype.renderSection=function(H,q,$,Z,z){var K=this,b="",J=q.lookup(H[1]);function V(w){return K.render(w,q,$,z)}if(!J)return;if(Gh(J))for(var W=0,y=J.length;W0||!$))z[K]=Z+z[K];return z.join(` -`)};O.prototype.renderPartial=function(H,q,$,Z){if(!$)return;var z=this.getConfigTags(Z),K=m3($)?$(H[1]):$[H[1]];if(K!=null){var b=H[6],J=H[5],V=H[4],W=K;if(J==0&&V)W=this.indentPartial(K,V,b);var y=this.parse(W,z);return this.renderTokens(y,q,$,W,Z)}};O.prototype.unescapedValue=function(H,q){var $=q.lookup(H[1]);if($!=null)return $};O.prototype.escapedValue=function(H,q,$){var Z=this.getConfigEscape($)||p.escape,z=q.lookup(H[1]);if(z!=null)return typeof z==="number"&&Z===p.escape?String(z):Z(z)};O.prototype.rawValue=function(H){return H[1]};O.prototype.getConfigTags=function(H){if(Gh(H))return H;else if(H&&typeof H==="object")return H.tags;else return};O.prototype.getConfigEscape=function(H){if(H&&typeof H==="object"&&!Gh(H))return H.escape;else return};var p={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(h){Yh.templateCache=h},get templateCache(){return Yh.templateCache}},Yh=new O;p.clearCache=function(){return Yh.clearCache()};p.parse=function(H,q){return Yh.parse(H,q)};p.render=function(H,q,$,Z){if(typeof H!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+FH(H)+'" was given as the first argument for mustache#render(template, view, partials)');return Yh.render(H,q,$,Z)};p.escape=SH;p.Scanner=Mh;p.Context=yh;p.Writer=O;var Hh=p;var y3=(h)=>h.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),IH=/^-?[0-9]+(\.[0-9]+)?$/,H2=(h)=>/^[=+\-@\t\r]/.test(h)&&!IH.test(h)?"'"+h:h,RH=(h)=>{let H=H2(h);return/[",\n\r]/.test(H)?`"${H.replace(/"/g,'""')}"`:H},iH=(h)=>JSON.stringify(h).slice(1,-1),h2=(h)=>h,q2={text:h2,markdown:h2,html:y3,xml:y3,json:iH,csv:RH,spreadsheet:(h)=>H2(y3(h))};var $2="has";function ah(h){return"has"+cH(h)}var kh="-last";function cH(h){if(h.length===0)return h;let H=h.charAt(0);if(H===H.toUpperCase()&&H!==H.toLowerCase())return h;return H.toUpperCase()+h.slice(1)}function Z2(h){if(h===null||h===void 0)return!1;if(typeof h==="string")return h.trim().length>0;if(Array.isArray(h))return h.length>0;if(typeof h==="number"||typeof h==="boolean"||typeof h==="bigint")return;return typeof h==="object"}function z2(h,H=0){return lh(h,H,void 0)}function lh(h,H,q){if(H>32)return h;if(Array.isArray(h)){let K=h.length-1;return h.map((b,J)=>lh(b,H+1,J===K))}if(h===null||typeof h!=="object")return h;let $=Object.getPrototypeOf(h);if($!==Object.prototype&&$!==null)return sH(h,H,q);let Z=h,z={};for(let[K,b]of Object.entries(Z))z[K]=lh(b,H+1,void 0);for(let[K,b]of Object.entries(Z)){let J=ah(K);if(Object.prototype.hasOwnProperty.call(Z,J))continue;let V=Z2(b);if(V!==void 0)z[J]=V}if(q!==void 0&&!Object.prototype.hasOwnProperty.call(Z,kh))z[kh]=q;return z}function pH(h){return h.length===0?h:h.charAt(0).toLowerCase()+h.slice(1)}function sH(h,H,q){let $=new Map,Z=(K)=>{if($.has(K))return $.get(K);let b=Reflect.get(h,K,h),J=typeof b==="function"?(...V)=>lh(Reflect.apply(b,h,V),H+1,void 0):lh(b,H+1,void 0);return $.set(K,J),J},z=(K)=>{if(typeof K!=="string")return;if(K===kh)return q;if(!K.startsWith("has"))return;let b=K.slice(3);for(let J of[pH(b),b]){if(!(J in h)||ah(J)!==K)continue;let V=Reflect.get(h,J,h);if(typeof V==="function")continue;let W=Z2(V);if(W!==void 0)return W}return};return new Proxy(Object.create(null),{has:(K,b)=>(b in h)||z(b)!==void 0,get:(K,b)=>(b in h)?Z(b):z(b)})}var b2=["mustache","jinja"],gh="mustache",e="jinja";var K2=[".jinja",".j2",".jinja2"];function qh(h,H,q){let $=h.engineOf?.(H);return $!==void 0&&$!==q}function th(h,H){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${h} is not a ${H} template; a ${H} body includes only ${H} partials`}function X2(h,H,q){if(q!==void 0){if(!b2.includes(q))throw Error(`unknown template engine ${JSON.stringify(q)}; expected one of ${b2.join(", ")}`);return q}if(h!==void 0&&H!==void 0){let $=h.engineOf?.(H);if($!==void 0)return $}return"mustache"}var R="ERR_VAR_NOT_ON_PAYLOAD",Uh="ERR_PARTIAL_UNRESOLVED",G3="ERR_REQUIRED_SLOT_UNUSED";var Sh="ERR_TEMPLATE_NOT_STATIC",$h="ERR_TEMPLATE_SYNTAX",xh="ERR_TEMPLATE_ENGINE_UNSUPPORTED",t=32,aH=new Set([">"," ","\t",` -`,"\r"]);function tH(h,H){let q=`<${H}`;for(let $=h.indexOf(q);$!==-1;$=h.indexOf(q,$+1)){let Z=h[$+q.length];if(Z!==void 0&&aH.has(Z))return!0}return!1}function nH(h,H){return h.includes(``)}function nh(h,H,q){let $=[];for(let z of q?.requiredSlots??[])if(!h.has(z))$.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:z});let Z=q?.requiredTags??[];if(Z.length>0){let z=H.join(` -`);for(let K of Z)if(!tH(z,K)||!nH(z,K))$.push({code:"ERR_OUTPUT_TAG_MISSING",path:K})}return $}var _H=()=>{throw Error("the explorer app renders Mustache only")},C3=new Proxy({},{get:()=>_H});var Zh=C3;function Lh(h){return Zh.parser.parse(h)}function zh(h){return typeof h==="object"&&h!==null&&typeof h.typename==="string"}function I(h){let H=[],q=($)=>{if(Array.isArray($))$.forEach(q);else if(zh($))H.push($)};for(let $ of h.fields)q(h[$]);if(h.typename==="Set")q(h.body);return H}function Nh(h){for(let H of K2)if(h.toLowerCase().endsWith(H))return h.slice(0,-H.length);return h}function TH(h){return function(H,q){this._emit("runtime.markSafe("),h.call(this,H,q),this._emit(")")}}function EH(h){let H={getSource(q){let $=h.resolve(Nh(q));return $===void 0?null:{src:$,path:q,noCache:!0}}};return new C3.Environment(H,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function rH(h){if(h===void 0)throw Error(`render verify failed: ${R}`);return h}function W2(h,H,q,$){let Z=EH(q),z=Zh.compiler.Compiler.prototype,K=Zh.lib.escape,b=z.compileCapture,J=Zh.runtime.ensureDefined;Zh.runtime.ensureDefined=rH,Zh.lib.escape=(V)=>$(typeof V==="string"?V:String(V)),z.compileCapture=TH(b);try{return Z.renderString(h,H)}finally{Zh.lib.escape=K,z.compileCapture=b,Zh.runtime.ensureDefined=J}}var S={tag:"opaque"},oH=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),eH=new Set(["first","last","random"]),hq=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),Hq=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),qq="attribute";function J2(h,H){return{tag:"typed",fields:h.fields,isArray:h.isArray===!0,path:H}}function Q2(h,H){if(h.tag==="opaque")return S;return{tag:"typed",fields:h.isArray?h.fields:void 0,isArray:!1,path:H}}function u3(h){if(h.kind==="key")return`.${h.key}`;if(h.kind==="index")return`[${h.index}]`;return"[*]"}function j2(h,H,q){let $=[],Z=q?.provider,z=new Set,K=[h],b=(j,Q)=>{$.push({code:j,path:Q})};function J(j,Q){for(let G=Q.frames.length-1;G>=0;G--){let u=Q.frames[G].get(j);if(u!==void 0)return u}let m=Q.root.find((G)=>G.name===j);if(m!==void 0){if(Q.root===H)z.add(j);return J2(m,j)}return oH.has(j)?S:void 0}function V(j,Q,m){j.frames[j.frames.length-1].set(Q,m)}function W(j){return{...j,frames:[...j.frames,new Map]}}function y(j){let Q=[],m=j;while(m.typename==="LookupVal"){let G=m.val;if(G.typename==="Literal"&&typeof G.value==="string")Q.unshift({kind:"key",key:G.value});else if(G.typename==="Literal"&&typeof G.value==="number")Q.unshift({kind:"index",index:G.value});else Q.unshift({kind:"dynamic",node:G});m=m.target}return{base:m,segments:Q}}function w(j,Q){let{base:m,segments:G}=y(j);for(let L of G)if(L.kind==="dynamic")B(L.node,Q);let u,M;if(m.typename==="Symbol"){M=m.value;let L=M+G.map(u3).join(""),c=J(M,Q);if(c===void 0)return b(R,L),S;u=c}else u=B(m,Q),M=u.tag==="typed"?u.path:"";let s=M+G.map(u3).join("");for(let L of G){if(u.tag==="opaque")return S;if(M+=u3(L),L.kind==="key"){let c=u.isArray?void 0:u.fields?.find((mh)=>mh.name===L.key);if(c===void 0)return b(R,s),S;u=J2(c,M)}else if(u.isArray)u={tag:"typed",fields:u.fields,isArray:!1,path:M};else if(L.kind==="dynamic"&&u.fields!==void 0)return b(Sh,s),S;else u={tag:"typed",fields:u.fields,isArray:!1,path:M}}return u}function v(j,Q,m){if(j.tag==="opaque"){B(Q,m);return}if(Q.typename!=="Literal"||typeof Q.value!=="string"){B(Q,m),b(Sh,`${j.path}[*]`);return}let G=Q.value,u=j.fields;for(let M of G.split(".")){let s=u?.find((L)=>L.name===M);if(s===void 0){b(R,`${j.path}.${G}`);return}u=s.fields}}function l(j){let Q=[],m=[];for(let G of j===void 0?[]:I(j))if(G.typename==="KeywordArgs")for(let u of I(G)){let M=u.key;m.push([String(M.value),u.value])}else Q.push(G);return{positional:Q,keywords:m}}function k(j,Q){let m=String(j.name.value),{positional:G,keywords:u}=l(j.args),[M,...s]=G,L=M===void 0?S:B(M,Q);s.forEach((c,mh)=>{if(mh===Hq.get(m))v(L,c,Q);else B(c,Q)});for(let[c,mh]of u)if(c===qq)v(L,mh,Q);else B(mh,Q);if(eH.has(m))return L.tag==="typed"?Q2(L,`${L.path}|${m}`):S;if(hq.has(m))return L;return S}function D(j,Q){let m=j.name;if(m.typename==="LookupVal")B(m.target,Q);else if(m.typename==="Symbol"){let M=m.value;if(J(M,Q)===void 0)b(R,M)}else B(m,Q);let{positional:G,keywords:u}=l(j.args);return G.forEach((M)=>B(M,Q)),u.forEach(([,M])=>B(M,Q)),S}function g(j,Q){let m=W(Q);for(let G of["caller","varargs","kwargs"])V(m,G,S);for(let G of I(j.args))if(G.typename==="Symbol")V(m,G.value,S);else if(G.typename==="KeywordArgs")for(let u of I(G))B(u.value,Q),V(m,String(u.key.value),S);C(j.body,m)}function F(j,Q,m,G,u=!1){if(Q.typename!=="Literal"||typeof Q.value!=="string"){B(Q,m),b(Sh,j);return}if(Z===void 0)return;let M=Nh(Q.value);if(m.seen.includes(M)||m.seen.length>=t)return;let s=Z.resolve(M);if(s===void 0){if(!u)b(Uh,M);return}if(qh(Z,M,e)){b(xh,M);return}K.push(s);let L;try{L=Lh(s)}catch(c){b($h,`${M}: ${c.message}`);return}C(L,G(m,M))}function d(j,Q,m){if(j.typename==="Symbol")V(m,j.value,Q);else for(let G of I(j))d(G,S,m)}function B(j,Q){switch(j.typename){case"Symbol":case"LookupVal":return w(j,Q);case"Literal":case"TemplateData":return S;case"Group":{let m=I(j);if(m.length===1)return B(m[0],Q);return m.forEach((G)=>B(G,Q)),S}case"Filter":case"FilterAsync":return k(j,Q);case"FunCall":return D(j,Q);case"Caller":return g(j,Q),S;case"Is":{B(j.left,Q);let m=j.right;if(m.typename==="FunCall"){let{positional:G,keywords:u}=l(m.args);G.forEach((M)=>B(M,Q)),u.forEach(([,M])=>B(M,Q))}return S}case"Pair":{let m=j.key;if(m.typename!=="Symbol")B(m,Q);return B(j.value,Q),S}case"Capture":return C(j.body,Q),S;default:for(let m of I(j))B(m,Q);return S}}function C(j,Q){switch(j.typename){case"Root":case"NodeList":for(let m of I(j))C(m,Q);return;case"Output":for(let m of I(j))B(m,Q);return;case"If":case"IfAsync":{if(B(j.cond,Q),C(j.body,Q),zh(j.else_))C(j.else_,Q);return}case"For":case"AsyncEach":case"AsyncAll":{let m=B(j.arr,Q),G=W(Q);V(G,"loop",S);let u=j.name;if(u.typename==="Symbol"){let M=u.value;V(G,M,Q2(m,M))}else d(u,S,G);if(C(j.body,G),zh(j.else_))C(j.else_,Q);return}case"Set":{let m=j.targets.filter(zh),G=S;if(zh(j.value))G=B(j.value,Q);else if(zh(j.body))B(j.body,Q);for(let u of m){let M=u.value;V(Q,M,G.tag==="typed"&&m.length===1?{...G,path:M}:S)}return}case"Macro":V(Q,String(j.name.value),S),g(j,Q);return;case"Include":F("include",j.template,Q,(m,G)=>({...W(m),seen:[...m.seen,G]}),j.ignoreMissing===!0);return;case"Import":case"FromImport":{let m=j.withContext===!0;if(F("import",j.template,Q,(G,u)=>({frames:[new Map],root:m?H:[],seen:[...G.seen,u]})),j.typename==="Import")V(Q,String(j.target.value),S);else for(let G of I(j.names)){let u=G.typename==="Pair"?G.value:G;V(Q,String(u.value),S)}return}case"Extends":F("extends",j.template,Q,(m,G)=>({frames:[new Map],root:H,seen:[...m.seen,G]}));return;case"Block":C(j.body,Q);return;case"Switch":{B(j.expr,Q);for(let m of I(j.cases))B(m.cond,Q),C(m.body,Q);if(zh(j.default))C(j.default,Q);return}default:B(j,Q)}}let Y;try{Y=Lh(h)}catch(j){return[{code:$h,path:j.message}]}return C(Y,{frames:[new Map],root:H,seen:[]}),$.push(...nh(z,K,q)),$}function w2(h,H){if(H.includes("."))return!1;if(!H.startsWith($2))return!1;for(let q=h.length-1;q>=0;q--)for(let $ of h[q])if(H===ah($.name))return!0;return!1}function V2(h,H){return h&&H===kh}function d2(h,H){return h.find((q)=>q.name===H)}function $q(h,H){let q=H.split("."),$;for(let Z=h.length-1;Z>=0;Z--){let z=d2(h[Z],q[0]);if(z){$=z;break}}for(let Z=1;$&&ZH[0]===Zq).map((H)=>[H[1],H[2],H[3]])}function Kq(h){return Th(h).some((H)=>H[0]===bq)}function _h(h,H){if(!Kq(h))return;return H??B3(h)[0]?.[0]}function Xq(h){return Th(h).filter((H)=>H[0]===zq).map((H)=>[H[2],H[3]])}function G2(h,H){let q="",$=0;for(let[Z,z]of Xq(H))q+=h.slice($,Z),$=z;return q+h.slice($)}function Wq(h){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(h instanceof Error?h.message:"")?.[1]}function u2(h){return C2(h)}function B2(h,H,q){if(q?.engine===e)return j2(h,H,q);let $=[],Z=q?.provider,z=H,K=new Set,b=[h];function J(y,w,v,l=!1){let k=w.length===1&&w[0]===z;for(let D of y){let g=D[0],F=D[1];switch(g){case"name":case"&":case"{":{if(F===".")break;if(k)K.add(F.split(".")[0]);if(!m2(w,F)&&!w2(w,F)&&!V2(l,F))$.push({code:R,path:F});break}case"#":case"^":{let d=Array.isArray(D[4])?D[4]:[];if(F==="."){J(d,w,v,l);break}if(k)K.add(F.split(".")[0]);let B=m2(w,F);if(!B){if(V2(l,F)){J(d,w,v,l);break}if(w2(w,F)){J(d,w,v,l);break}$.push({code:R,path:F});break}let C=g==="#"&&B.fields!==void 0,Y=g==="#"&&B.isArray===!0;J(d,C?[...w,B.fields]:w,v,Y?B.fields!==void 0:l);break}case">":{if(!Z)break;if(v.includes(F)||v.length>=t)break;let d=Z.resolve(F);if(d===void 0){$.push({code:Uh,path:F});break}if(qh(Z,F,gh)){$.push({code:xh,path:F});break}let B=y2(d);if(!Array.isArray(B)){$.push(B);break}let C=_h(B,F);if(C!==void 0)$.push({code:$h,path:C});b.push(G2(d,B)),J(B,w,[...v,F],l);break}default:break}}}let V=y2(h);if(!Array.isArray(V))return[V];let W=_h(V,void 0);if(W!==void 0)$.push({code:$h,path:W});return b[0]=G2(h,V),J(V,[z],[]),$.push(...nh(K,b,q)),$}var Jq=new Set(["Include","Import","FromImport","Extends"]);function v2(h,H){if(Jq.has(h.typename)){let q=h.template;if(q.typename==="Literal"&&typeof q.value==="string")H.push({ref:Nh(q.value),optional:h.ignoreMissing===!0})}for(let q of I(h))v2(q,H)}function D2(h,H,q){let $=[];v2(Lh(h),$);for(let{ref:Z,optional:z}of $){if(q.includes(Z))throw Error(`partial cycle: ${[...q,Z].join(" -> ")}`);if(q.length>=t)throw Error(`partial depth exceeded ${t}: ${Z}`);let K=H.resolve(Z);if(K===void 0){if(z)continue;throw Error(`unresolved partial: ${Z}`)}if(qh(H,Z,e))throw Error(th(Z,e));D2(K,H,[...q,Z])}}function F2(h,H,q,$,Z){return D2(h,$,H!==void 0?[H]:[]),W2(h,typeof q==="object"&&q!==null?q:{},$,Z)}function Y2(h,H,q,$){let Z=u2(h);if(_h(Z,$)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let z=B3(Z);if(z.length===0)return h;let K="",b=0;for(let[J,V,W]of z){if(q.includes(J))throw Error(`partial cycle: ${[...q,J].join(" -> ")}`);if(q.length>=t)throw Error(`partial depth exceeded ${t}: ${J}`);let y=H.resolve(J);if(y===void 0)throw Error(`unresolved partial: ${J}`);if(qh(H,J,gh))throw Error(th(J,gh));K+=h.slice(b,V)+Y2(y,H,[...q,J],J),b=W}return K+h.slice(b)}function v3(h){let H=h.template??(h.ref!==void 0?h.provider.resolve(h.ref):void 0);if(H===void 0)throw Error(`unresolved ref: ${h.ref??"(none)"}`);let q=X2(h.provider,h.template===void 0?h.ref:void 0,h.engine);if(h.verify!==void 0){let z=B2(H,h.verify,{provider:h.provider,engine:q}).filter((K)=>K.code!==G3);if(z.length>0)throw Error(`render verify failed: ${z.map((K)=>`${K.code} (${K.path})`).join(", ")}`)}let $=q2[h.format??"text"],Z=q===e?F2(H,h.template===void 0?h.ref:void 0,h.payload,h.provider,$):jq(H,h,$);if(h.maxChars!==void 0&&Z.length>h.maxChars)throw Error(`render exceeded maxChars budget: ${Z.length} > ${h.maxChars}`);return Z}function Qq(){let h=Hh.Writer.prototype,H={escapedValue:h.escapedValue,unescapedValue:h.unescapedValue};for(let q of["escapedValue","unescapedValue"]){let $=H[q];h[q]=function(Z,z,...K){let b=String(Z[1]);if(z.lookup(b)===void 0)throw Error(`render verify failed: ${R} (${b})`);return $.call(this,Z,z,...K)}}return()=>{h.escapedValue=H.escapedValue,h.unescapedValue=H.unescapedValue}}function jq(h,H,q){let $=Y2(h,H.provider,H.ref!==void 0?[H.ref]:[]),Z=Hh.escape;Hh.escape=(b)=>q(typeof b==="string"?b:String(b));let z,K=Qq();try{z=Hh.render($,z2(H.payload),{})}finally{Hh.escape=Z,K()}return z}class Eh{map;engine;constructor(h,H={}){this.map=h;this.engine=H.engine}resolve(h){return Object.prototype.hasOwnProperty.call(this.map,h)?this.map[h]:void 0}engineOf(h){return this.resolve(h)===void 0?void 0:this.engine}}var rh="object",oh="field";var eh="identity",h3="relationship",M2="layout",k2="source",D3="origin",H3="template",F3="index",bh="requirement",fh="dimension",Oh="measure",Ph="segment";var Wh="description",l2="summary";var Ch="string";var g2="currency",Ah="enum",U2="uuid",S2="uri",x2="inet",L2="duration";var Y3="required";var M3="default",k3="maxLength";var N2="filterable",f2="sortable";var q3="objectRef";var l3="values";var g3="fields";var U3="references";var S3="entity",O2="value",P2="projection",A2="report";var $3="from",I2="dimensions",R2="measures",i2="segment",x3="filter",c2="spine";var N="eq",P="ne",n="gt",_="gte",T="lt",E="lte",A="in",L3="like",f="isNull";var R1={string:[N,P,A,L3,f],[Ah]:[N,P,A,L3,f],int:[N,P,n,_,T,E,A,f],long:[N,P,n,_,T,E,A,f],double:[N,P,n,_,T,E,A,f],float:[N,P,n,_,T,E,A,f],decimal:[N,P,n,_,T,E,A,f],[g2]:[N,P,n,_,T,E,A,f],boolean:[N,f],date:[N,P,n,_,T,E,A,f],time:[N,P,n,_,T,E,A,f],timestamp:[N,P,n,_,T,E,A,f],[U2]:[N,P,A,f],[S2]:[N,P,A,L3,f],[x2]:[N,P,A,f],[L2]:[N,P,n,_,T,E,A,f]};var wq="association",Vq="aggregation",dq="composition";var p2="cardinality",s2="objectRef",a2="through";var p1={[dq]:"cascade",[Vq]:"set-null",[wq]:"restrict"};var i="functional",Jh="architectural";var Z3="disposition",t2="trackedBy",uh="statement",n2="counterexample";var Qh="planned",Ih="live",N3="partial",f3="retired",_2=["planned","live","partial","retired"];var T2=["planned","partial"];var O3=3,P3=4;var z3="from";var E2="agg",b3="of",A3="via",I3="filter";var R3="expr";var mq=["count","sum","avg","min","max"];var r2="any",o2="all",yq="collect",E1=[...mq,r2,o2,yq];var e2="of",hH="via",HH="grains",qH="agg";var i3="filter",$H="segment",ZH="numerator",zH="denominator";var c3="default";var bH="column";var Gq="uuid",Cq="jsonb";var uq="text",Bq="varchar",vq="character varying";var Z5={[Gq]:[Ch],[Cq]:[Ch],[uq]:[Ch],[Bq]:[Ch],[vq]:[Ch]};var KH="table",XH="view";var WH="kind";var JH="view";var p3="pageSize",QH="defaultSortField",s3="defaultSortOrder";var jH="columns";var a3="prompt";var Rh="payloadRef",wH="textRef",K3="format";var X3="responseRef",VH="maxTokens";var dH="model";var mH="promptStyle";var yH="responseFormat";var jh=[Ih,N3,Qh,f3].filter((h)=>_2.includes(h)),t3={[Ih]:"●",[N3]:"◐",[Qh]:"○",[f3]:"⊘"},GH=(h,H)=>hH?1:0;class n3{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(h){this.view=h;for(let H of h.nodes){let q=this.file(H,H.package,void 0);this.topOf.set(H.id,H);for(let $ of H.memberGroups)for(let Z of $.members)this.fileMember(Z,H.package,q.id);if(H.type===rh)this.objects.push(q);else if(H.type===H3)this.templates.push(q);else if(H.type!==bh)this.others.push(q)}for(let H of this.kids.values())H.sort((q,$)=>q.order-$.order||GH(q.id,$.id));this.packages=h.packages.map((H)=>H.name);for(let H of h.requirements){let q=this.byId.get(H.id);if(q===void 0)continue;let $=H.parent!==null?this.reqById.get(H.parent.id):void 0,Z={node:q,req:H,...$!==void 0?{parent:$}:{},children:[],...H.level!==null?{level:H.level}:{},status:H.status,kind:H.subType};if(this.requirements.push(Z),this.reqById.set(H.id,Z),$!==void 0)$.children.push(Z);else this.topRequirements.push(Z)}}file(h,H,q){let $={};for(let K of h.attrs)$[K.name]=K.value;let Z="declaredOn"in h?h.declaredOn:null,z={id:h.id,type:h.type,subType:h.subType,name:h.name,package:H,order:h.order,...q!==void 0?{parent:q}:{},path:h.path,anchor:"anchor"in h?h.anchor:"",...h.extends!==null&&!h.extends.unresolved?{extends:h.extends.id}:{},abstract:h.abstract,isArray:"isArray"in h?h.isArray:!1,...Z!==null&&!Z.unresolved?{inheritedFrom:Z.id}:{},attrs:$,view:h};if(this.byId.set(z.id,z),q!==void 0)this.kids.set(q,[...this.kids.get(q)??[],z]);return z}fileMember(h,H,q){this.file(h,H,q);for(let $ of h.memberGroups)for(let Z of $.members)this.fileMember(Z,H,h.id)}children(h){return this.kids.get(h)??[]}ownerOf(h){let H=this.byId.get(h);while(H?.parent!==void 0)H=this.byId.get(H.parent);return H?.id??h}top(h){return this.topOf.get(h)}fields(h){return this.children(h).filter((H)=>H.type===oh)}source(h){return this.children(h).find((H)=>H.type===k2)}storage(h){let H=this.source(h);if(H===void 0)return;let q=H.attrs[XH],$=H.attrs[KH],Z=H.attrs[WH]===JH||typeof q==="string",z=typeof q==="string"?q:typeof $==="string"?$:void 0;return{kind:Z?"view":"table",...z!==void 0?{name:z}:{}}}isEntity(h){return h.type===rh&&h.subType===S3}isPrompt(h){return h.type===H3&&h.subType===a3}kindOf(h){if(h.type===H3)return h.subType===a3?"prompt":"template";if(h.type!==rh)return"other";if(h.subType===S3)return"entity";if(h.subType===O2)return"value";if(h.subType===P2)return"projection";if(h.subType===A2)return"report";return"object"}storedEntities(){return this.objects.filter((h)=>this.isEntity(h)&&!h.abstract)}claims(h){let H=this.byId.get(h)?.view;if(H===void 0)return[];return H.claims.flatMap((q)=>{let $=this.reqById.get(q.requirement.id);return $===void 0?[]:[{req:$,...q.member!==""?{member:q.member}:{}}]})}generated(h){return(this.topOf.get(h)?.files??[]).flatMap((H)=>H.paths.map((q)=>({path:q,generatedBy:H.generatedBy})))}routes(h){return this.topOf.get(h)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(h){let H=[],q=($)=>{H.push($);for(let Z of $.children)q(Z)};return q(h),H}below(h){return this.subtree(h).slice(1)}rollup(h){let H={};for(let q of h.req.rollup)if(q.count>0)H[q.status]=q.count;return H}targetsOf(h){return h.req.targets.map((H)=>H.id)}linkTargets(h){return h.req.implementedBy.filter((H)=>H.resolves&&this.byId.has(H.target.id)).map((H)=>H.target.id)}featureOf(h){let H=new Map;for(let $ of this.claims(h)){let Z=$.req;while(Z.parent!==void 0)Z=Z.parent;if(Z.kind!==i)continue;H.set(Z,(H.get(Z)??0)+1)}let q;for(let $ of this.features()){let Z=H.get($)??0;if(Z>0&&(q===void 0||Z>(H.get(q)??0)))q=$}return q}features(){return this.topRequirements.filter((h)=>h.kind===i)}qualities(){return this.topRequirements.filter((h)=>h.kind===Jh)}claimStatus(h){let H=this.claims(h);if(H.length===0)return"unclaimed";for(let q of jh)if(H.some(($)=>$.req.status===q))return q;return"unclaimed"}modelEdges(){let h=[],H=new Set;for(let q of this.view.nodes){if(q.type===bh)continue;for(let $ of q.refs){let Z=this.ownerOf($.target.id),z=this.byId.get(Z);if(Z===q.id||z===void 0||z.type===bh)continue;let K=`${$.attr}\x00${q.id}\x00${Z}`;if(H.has(K))continue;H.add(K),h.push({kind:$.attr,from:q.id,to:Z,...$.via!==null?{via:$.via.id}:{}})}}return h.sort((q,$)=>GH(`${q.kind}\x00${q.from}\x00${q.to}`,`${$.kind}\x00${$.from}\x00${$.to}`))}slice(h){return this.view.slices.find((H)=>H.id===h)}}function X(h){return String(h??"").replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H])}function a(h){if(h==="")return"";return`${t3[h]??""} ${X(h)}`}function W3(h){if(h==="")return"";return`${t3[h]??""}`}function r(h){return h.level!==void 0?`L${h.level}`:'—'}var Bh="gate";function J3(h){let H=h.req.diagnostics.filter((z)=>z.source===Bh);if(H.length===0)return"";let q=H.some((z)=>z.severity==="error")?"error":"warn",$=H.map((z)=>z.code).join(", "),Z=H.length;return`${q==="error"?"✕":"!"} ${Z} gate ${q==="error"?Z===1?"error":"errors":Z===1?"warning":"warnings"}`}function _3(h){let H=h.node.attrs[Z3];return typeof H==="string"?`${X(H)}`:""}function ih(h){let H=jh.reduce((Z,z)=>Z+(h[z]??0),0),q=jh.filter((Z)=>(h[Z]??0)>0).map((Z)=>`${h[Z]} ${Z}`).join(", ");if(H===0)return'
    ';let $=jh.filter((Z)=>(h[Z]??0)>0).map((Z)=>``).join("");return``}function Dq(h){return`${(Math.round(h*1e4)/100).toString()}%`}function CH(h){return`
    ${jh.map(($)=>a($)).join("")}${h?'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 U(h,H){let q=h.split("/").length-1;return"../".repeat(q)+H}var j3="index.html",Vh="map.html",dh="requirements/features.html",ch="requirements/qualities.html",w3="matrix.html",ph="trace.html",Dh="prompts.html",Fh="api.html",sh="gaps.html",vh="model/index.html",Fq=new Set([oh,eh,F3,h3,fh,Oh,Ph]),Yq=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),Mq="WARN_REQUIREMENT_OBJECT_UNCLAIMED",wh=(h,H)=>hH?1:0,x=(h)=>typeof h==="string"?h:void 0,o=(h)=>Array.isArray(h)?h.filter((H)=>typeof H==="string"):typeof h==="string"?[h]:[];function kq(h){return h===""?"-root":h.split("::").join("/")}function Kh(h){let H=h.lastIndexOf("::");return H<0?h:h.slice(H+2)}class E3{ix;constructor(h){this.ix=h}objectPage(h){return h.path}packagePage(h){return`model/${kq(h)}/index.html`}reqPage(h){return h.req.path}reqPath(h){return h.req.address}reqLabel(h){return h.req.label}pageOf(h){let H=this.ix.byId.get(h)?.path;return H===void 0||H===""?void 0:H}implLinks(h){return h.req.implementedBy.map((H)=>({ref:H.ref,resolves:H.resolves,...H.resolves&&this.ix.byId.has(H.target.id)?{target:H.target.id}:{}}))}attrValues(h,H){return h.view.attrs.find((q)=>q.name===H)?.values??[]}refLinks(h,H){return this.attrValues(h,H).flatMap((q)=>q.link!==null&&!q.link.unresolved?[q.link]:[])}refHtml(h,H,q,$){return this.attrValues(H,q).filter((Z)=>Z.link!==null).map((Z)=>this.viewLink(h,Z.link,$?.(Z.text))).join(", ")}viewLink(h,H,q){return H.unresolved?`${X(q??Kh(H.label))} (unresolved)`:this.link(h,H.id,q)}memberAnchors(h,H){return this.ix.children(h.id).filter((q)=>!H.has(q.type)&&q.anchor!=="").map((q)=>``).join("")}kindClass(h){return`k-${this.ix.kindOf(h)}`}link(h,H,q){let $=this.pageOf(H),Z=this.ix.byId.get(this.ix.ownerOf(H));if($===void 0||Z===void 0)return`${X(q??Kh(H))} (unresolved)`;let z=this.ix.reqById.get(H),K=q??(z!==void 0?this.reqLabel(z):H===Z.id?Z.name:`${Z.name}.${H.slice(Z.id.length+1)}`);return`${X(K)}`}reqLink(h,H){return`${X(this.reqLabel(H))}`}description(h){return X(x(h.attrs[Wh])??x(h.attrs[l2])??"")}topOf(h){let H=h;while(H.parent!==void 0)H=H.parent;return H}overview(h){let H=this.ix,q=j3,$=H.storedEntities(),Z=H.objects.filter((w)=>H.isEntity(w)&&w.abstract===!0).length,z=H.templates.filter((w)=>H.isPrompt(w)),K=H.objects.filter((w)=>H.kindOf(w)==="value").length,b=H.objects.filter((w)=>H.kindOf(w)==="projection").length,J=H.objects.filter((w)=>H.kindOf(w)==="report").length,V=H.view.counts,W=[];if(W.push({n:`${$.length}`,l:`stored entities${Z>0?` (${Z} abstract base${Z===1?"":"s"})`:""}`,href:U(q,Vh)}),W.push({n:`${z.length}`,l:`declared prompt${z.length===1?"":"s"}, ${T3(K,"payload or reply type","payload and reply types")}`,href:U(q,Dh)}),H.hasRequirements())W.push({n:`${V.requirements}`,l:`requirements: ${T3(V.functional,"feature")}, ${T3(V.architectural,"quality","qualities")}`,href:U(q,dh)});else W.push({n:`${b+J}`,l:`read models: ${b} projection${b===1?"":"s"}, ${J} report${J===1?"":"s"}`,href:U(q,vh)});if(V.coverageMeasured&&V.entitiesTotal>0)W.push({n:`${V.entitiesClaimed}/${V.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:U(q,sh)});else W.push({n:`${H.packages.length}`,l:`package${H.packages.length===1?"":"s"} in the model`,href:U(q,vh)});if(H.view.sources.routes){let w=H.objects.filter((v)=>H.routes(v.id).length>0).length;W.push({n:`${w}`,l:"objects with mounted REST routes",href:U(q,Fh)})}else W.push({n:"—",l:"REST routes: none recorded by this run",href:U(q,Fh)});W.push({n:H.view.sources.files?`${V.files}`:"—",l:H.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:U(q,ph)});let y=["the effective model"];if(H.view.sources.requirements)y.push("the requirement gate's ledger");if(H.view.sources.files)y.push("the generation manifest");return{heading:X(`What ${h} does`),sourcesLine:X(lq(y)),tiles:W.map((w)=>({n:X(w.n),l:X(w.l),href:X(w.href)})),hasRequirements:H.hasRequirements(),featureCards:H.features().map((w)=>this.capCard(q,w)),qualityCards:H.qualities().map((w)=>this.capCard(q,w)),hasFeatures:H.features().length>0,hasQualities:H.qualities().length>0,packageCards:H.packages.map((w)=>this.packageCard(q,w))}}capCard(h,H){let q=this.ix.below(H).length,$=this.ix.targetsOf(H).length;return{levelHtml:r(H),linkHtml:this.reqLink(h,H),statusHtml:a(H.status),verdictHtml:J3(H),statement:X(x(H.node.attrs[uh])??""),barHtml:ih(this.ix.rollup(H)),countsLine:X(`${q} requirement${q===1?"":"s"} below · ${$} model node${$===1?"":"s"} claimed`),children:H.children.map((Z)=>({levelHtml:r(Z),linkHtml:this.reqLink(h,Z),glyphHtml:W3(Z.status)})),hasChildren:H.children.length>0}}packageCard(h,H){let q=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((b)=>b.package===H),$=new Map;for(let b of q)$.set(this.ix.kindOf(b),($.get(this.ix.kindOf(b))??0)+1);let z=["entity","value","projection","report","prompt","template","object","other"].filter((b)=>$.has(b)).map((b)=>`● ${$.get(b)} ${gq(b,$.get(b)??0)}`).join(" · "),K=q.slice(0,12);return{name:X(H===""?"(no package)":H),href:X(U(h,this.packagePage(H))),kindLineHtml:z,membersHtml:K.map((b)=>this.link(h,b.id)).join(", ")+(q.length>K.length?` +${q.length-K.length}`:"")}}map(){let h=this.ix,H=[],q=[{value:"",label:"Whole model"}];if(h.templates.some(($)=>h.isPrompt($)))q.push({value:"@prompts",label:"Prompts and their payloads"});H.push({label:"Model",options:q});for(let $ of h.topRequirements){let Z=[];for(let z of[$,...$.children]){let K=h.slice(`requirement:${z.node.id}`);if(K===void 0)continue;let b=z===$?"":" ";Z.push({value:K.id,label:`${b}${z.level!==void 0?`L${z.level} `:""}${this.reqLabel(z)} (${h.targetsOf(z).length})`})}if(Z.length>0)H.push({label:`${$.kind===i?"Feature":"Quality"}: ${this.reqLabel($)}`,options:Z})}if(h.packages.length>1)H.push({label:"Package",options:h.packages.map(($)=>({value:`package:${$}`,label:$===""?"(no package)":$}))});return{sliceGroups:H.map(($)=>({label:X($.label),options:$.options.map((Z)=>({value:X(Z.value),label:X(Z.label)}))})),hasRequirements:h.hasRequirements()}}object(h){let H=this.ix,q=this.objectPage(h),$=H.kindOf(h),Z=H.claims(h.id),z=H.storage(h.id),K=z===void 0?$==="value"?"value object: no storage":"no source":`${z.kind}${z.name!==void 0?` ${z.name}`:""}`,b=H.fields(h.id).map((d)=>this.fieldRow(q,h,d)),J=b.some((d)=>d.column!==""),V=H.children(h.id).filter((d)=>d.type===eh||d.type===F3||d.type===h3).map((d)=>this.keyRow(q,d)),W=H.children(h.id).filter((d)=>d.type===fh||d.type===Oh||d.type===Ph).map((d)=>this.reportingRow(q,d)),y=H.children(h.id).filter((d)=>d.type===M2).map((d)=>this.layoutRow(d)),w=this.unclaimedEntity(h),v=this.whyRows(q,h),l=H.top(h.id)?.referencedBy??[],k=(d)=>d===Rh||d===X3,D=[...new Set(l.filter((d)=>k(d.attr)).map((d)=>d.from.id))].sort(wh).map((d)=>this.link(q,d)),g=[...new Set(l.filter((d)=>!k(d.attr)).map((d)=>d.from.id))].sort(wh).map((d)=>this.link(q,d)),F=h.extends!==void 0?this.link(q,h.extends):"";return{id:X(h.id),name:X(h.name),kindLabel:X(`object.${h.subType}`),crumbsHtml:`Model › ${X(h.package===""?"(no package)":h.package)} › object.${X(h.subType)}${this.memberAnchors(h,Fq)}`,isAbstract:h.abstract===!0,isUnclaimed:w,isReadOnly:z?.kind==="view",kindBadge:X($),description:this.description(h),storageLine:X(K),extendsHtml:F,whyRows:v,hasWhy:v.length>0,whyEmptyHtml:this.whyEmpty(h),fields:b,hasFields:b.length>0,hasColumn:J,showClaims:this.ix.hasRequirements(),keys:V,hasKeys:V.length>0,reporting:W,hasReporting:W.length>0,layouts:y,hasLayouts:y.length>0,projection:$==="projection"?this.projectionBlock(q,h):void 0,report:$==="report"?this.reportBlock(q,h):void 0,routes:H.routes(h.id).map((d)=>({method:X(d.method),path:X(d.path)})),hasRoutes:H.routes(h.id).length>0,routesNote:!H.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:D.join(", "),referencedByHtml:g.join(", "),generated:this.generatedGroups(h.id),hasGenerated:H.generated(h.id).length>0,generatedNote:!H.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:Z.length}}unclaimedEntity(h){let H=this.ix;if(!H.isEntity(h)||h.abstract===!0)return!1;return H.top(h.id)?.unclaimed===!0}whyRows(h,H){let q=[...this.ix.claims(H.id)].sort((z,K)=>this.ix.requirements.indexOf(z.req)-this.ix.requirements.indexOf(K.req)),$=[],Z;for(let z of q){let K=this.topOf(z.req);$.push({capabilityHtml:K===Z?"":this.reqLink(h,K),reqHtml:this.reqLink(h,z.req),statement:X(x(z.req.node.attrs[uh])??""),levelHtml:r(z.req),statusHtml:a(z.req.status),onHtml:z.member!==void 0?`${X(z.member)}`:'whole object'}),Z=K}return $}whyEmpty(h){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${X(h.name)} exists.`;if(this.unclaimedEntity(h))return`No requirement claims ${X(h.name)}. The gate reports this as ${Mq}.`;return`No requirement claims ${X(h.name)}.`}fieldRow(h,H,q){let $=this.refHtml(h,q,q3),Z=q.subType===Ah?o(q.attrs[l3]):[],z=[];if(q.attrs[Y3]===!0)z.push("required");if(q.attrs[N2]===!0)z.push("filterable");if(q.attrs[f2]===!0)z.push("sortable");if(q.attrs[k3]!==void 0)z.push(`max ${String(q.attrs[k3])}`);if(q.attrs[M3]!==void 0)z.push(`default ${Xh(q.attrs[M3])}`);if(this.ix.children(q.id).some((b)=>b.type===D3))z.push("derived");let K=this.ix.claims(H.id).filter((b)=>b.member!==void 0&&b.member.split(".")[0]===q.name);return{anchor:X(q.anchor),name:X(q.name),inheritedHtml:q.inheritedFrom!==void 0?`inherited`:"",type:X(`${q.subType}${q.isArray===!0?"[]":""}`),refHtml:$!==""?` → ${$}`:"",valuesHtml:Z.length>0?`
    ${Z.map(X).join(" | ")}
    `:"",column:X(x(q.attrs[bH])??""),flagsHtml:z.map((b)=>`${X(b)}`).join(""),claimsHtml:K.map((b)=>`${W3(b.req.status)} ${X(this.reqLabel(b.req))}`).join("
    ")}}keyRow(h,H){let q=o(H.attrs[g3]),$=this.refHtml(h,H,U3)||this.refHtml(h,H,s2),Z=x(H.attrs[a2]),z=x(H.attrs[p2]),K=H.type===h3?[z,Z!==void 0?`through ${Kh(Z)}`:void 0].filter((b)=>b!==void 0).join(", "):`(${q.join(", ")})`;return{anchor:X(H.anchor),kind:X(`${H.type}.${H.subType}`),name:X(H.name),inheritedHtml:H.inheritedFrom!==void 0?'inherited':"",shape:X(K),targetHtml:$!==""?`→ ${$}`:""}}reportingRow(h,H){let q=H.attrs,$=[],Z=x(q[qH]),z=this.refHtml(h,H,e2,Kh);if(Z!==void 0)$.push(`${X(Z)}(${z})`);else if(z!=="")$.push(`of ${z}`);let K=x(q[ZH]),b=x(q[zH]);if(K!==void 0&&b!==void 0)$.push(`${X(K)} ÷ ${X(b)}`);let J=x(q[hH]);if(J!==void 0)$.push(`via ${X(Kh(J))}`);let V=o(q[HH]);if(V.length>0)$.push(`grains ${V.map((y)=>`${X(y)}`).join(" ")}`);let W=x(q[$H]);if(W!==void 0)$.push(`segment ${X(W)}`);if(q[i3]!==void 0)$.push(`filter ${X(Xh(q[i3]))}`);if(q[c3]!==void 0)$.push(`default ${X(Xh(q[c3]))}`);return{anchor:X(H.anchor),kind:X(`${H.type}.${H.subType}`),name:X(H.name),definitionHtml:$.join(" · ")}}layoutRow(h){let H=[],q=o(h.attrs[jH]);if(q.length>0)H.push(`columns ${q.map((Z)=>`${X(Z)}`).join(", ")}`);let $=x(h.attrs[QH]);if($!==void 0)H.push(`sorted by ${X($)}${x(h.attrs[s3])!==void 0?` ${X(x(h.attrs[s3]))}`:""}`);if(typeof h.attrs[p3]==="number")H.push(`${h.attrs[p3]} per page`);return{kind:X(`${h.type}.${h.subType}`),name:X(h.name),detailHtml:H.join(", ")}}projectionBlock(h,H){let q=this.ix,$=[],Z=new Set;for(let z of q.fields(H.id)){if(z.extends!==void 0)Z.add(q.ownerOf(z.extends));for(let K of q.children(z.id).filter((b)=>b.type===D3)){let b=this.originDefinition(h,K);for(let J of this.refLinks(K,z3))Z.add(q.ownerOf(J.id));$.push({field:X(z.name),origin:X(`origin.${K.subType}`),definitionHtml:b})}}return{basesHtml:[...Z].filter((z)=>z!==H.id).sort(wh).map((z)=>this.link(h,z)).join(", "),origins:$,hasOrigins:$.length>0}}originDefinition(h,H){let q=H.attrs,$=(K)=>this.attrValues(H,K).map((b)=>b.link!==null&&!b.link.unresolved?this.link(h,b.link.id,Kh(b.text)):`${X(Kh(b.text))}`).join(", "),Z=[],z=x(q[E2]);if(z!==void 0)Z.push(`${X(z)}(${$(b3)})`);else if(q[b3]!==void 0)Z.push(`of ${$(b3)}`);if(q[z3]!==void 0)Z.push(`from ${$(z3)}`);if(q[A3]!==void 0)Z.push(`via ${X(Kh(String(q[A3])))}`);if(q[R3]!==void 0)Z.push(`${X(Xh(q[R3]))}`);if(q[I3]!==void 0)Z.push(`filter ${X(Xh(q[I3]))}`);return Z.join(" · ")}reportBlock(h,H){let q=H.attrs,$=this.refLinks(H,$3)[0]?.id??x(q[$3]),Z=(K,b)=>{let V=[$!==void 0?`${$}.${K}`:void 0,`${H.package===""?"":`${H.package}::`}${K}`].filter((W)=>W!==void 0).find((W)=>this.ix.byId.get(W)?.type===b||this.ix.byId.has(W)&&K.includes("."));return V!==void 0?this.link(h,V,K):`${X(K)}`},z=x(q[c2]);return{fromHtml:this.refHtml(h,H,$3),spineHtml:z!==void 0?`${X(z)}`:"",dimensionsHtml:o(q[I2]).map((K)=>Z(K,fh)).join(", "),measuresHtml:o(q[R2]).map((K)=>Z(K,Oh)).join(", "),segmentHtml:o(q[i2]).map((K)=>Z(K,Ph)).join(", "),filterHtml:q[x3]!==void 0?`${X(Xh(q[x3]))}`:""}}generatedGroups(h){let H=new Map;for(let q of this.ix.generated(h))H.set(q.generatedBy,[...H.get(q.generatedBy)??[],q.path]);return[...H.keys()].sort(wh).map((q)=>({generator:X(q),files:(H.get(q)??[]).map(($)=>X($))}))}node(h){let H=this.ix,q=this.objectPage(h),$=`${h.type}.${h.subType}`,Z=this.whyRows(q,h),z=this.attrRows(q,h),K=[...(H.top(h.id)?.referencedBy??[]).map((J)=>J.from.id),...H.claims(h.id).map((J)=>this.topOf(J.req).node.id)],b=[...new Set(K.filter((J)=>J!==h.id))].sort(wh).map((J)=>this.link(q,J));return{id:X(h.id),name:X(h.name),kindLabel:X($),crumbsHtml:`Model › ${X(h.package===""?"(no package)":h.package)} › ${X($)}`,isAbstract:h.abstract===!0,description:this.description(h),extendsHtml:h.extends!==void 0?this.link(q,h.extends):"",attrs:z,hasAttrs:z.length>0,members:H.children(h.id).map((J)=>({anchor:X(J.anchor),kind:X(`${J.type}.${J.subType}`),nameHtml:H.reqById.has(J.id)?this.link(q,J.id):X(J.name===""?`#${J.order}`:J.name),attrsHtml:this.attrRows(q,J).map((V)=>`@${V.name} ${V.valueHtml}`).join("
    "),below:H.children(J.id).length})),hasMembers:H.children(h.id).length>0,whyRows:Z,hasWhy:Z.length>0,whyEmptyHtml:this.whyEmpty(h),referencedByHtml:b.join(", "),generated:this.generatedGroups(h.id),hasGenerated:H.generated(h.id).length>0,generatedNote:!H.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(h,H){return H.view.attrs.map((q)=>{let $=q.values.filter((Z)=>Z.link!==null&&!Z.link.unresolved);return{name:X(q.name),valueHtml:$.length>0&&$.length===q.values.length?$.map((Z)=>this.link(h,Z.link.id)).join(", "):`${X(Xh(q.value))}`}})}prompt(h,H){let q=this.ix,$=this.objectPage(h),Z=this.refLinks(h,Rh)[0]?.id,z=this.refLinks(h,X3)[0]?.id,K=H!==void 0?uH(H):void 0,b=Z!==void 0?q.byId.get(Z):void 0,J=z!==void 0?q.byId.get(z):void 0,V=b!==void 0?q.fields(b.id).map((D)=>({name:X(D.name),requiredHtml:D.attrs[Y3]===!0?'required':"",type:X(`${D.subType}${D.isArray===!0?"[]":""}`),refHtml:this.refHtml($,D,q3)!==""?` → ${this.refHtml($,D,q3)}`:"",usedHtml:K===void 0?'text not read':K.has(D.name)?"yes":'no'})):[],W=J!==void 0?q.fields(J.id).map((D)=>({name:X(D.name),type:X(`${D.subType}${D.isArray===!0?"[]":""}`),valuesHtml:D.subType===Ah?`
    ${o(D.attrs[l3]).map(X).join(" | ")}
    `:""})):[],y=x(h.attrs[wH])??"",w=H!==void 0?H.replace(/\n$/,"").split(` -`).length:0,v=[K3,yH,mH,dH,VH].filter((D)=>h.attrs[D]!==void 0).map((D)=>`@${X(D)} ${X(Xh(h.attrs[D]))}`).join(""),l=q.claims(h.id),k=this.whyRows($,h);return{name:X(h.name),kindLabel:X(`template.${h.subType}`),crumbsHtml:`Prompts › ${X(h.package===""?"(no package)":h.package)} › template.${X(h.subType)}${this.memberAnchors(h,new Set)}`,isUnclaimed:q.hasClaims()&&l.length===0,description:this.description(h),attrsHtml:v,payloadHtml:b!==void 0?this.link($,b.id):"none",payloadRows:V,hasPayload:b!==void 0,replyHtml:J!==void 0?this.link($,J.id):"none",replyRows:W,hasReply:J!==void 0,textRef:X(y),textMeta:X(H!==void 0?`${y}.mustache · ${w} line${w===1?"":"s"}${x(h.attrs[K3])!==void 0?` · ${x(h.attrs[K3])}`:""}`:`${y}.mustache`),textHtml:H!==void 0?Sq(H):"",hasText:H!==void 0,generated:this.generatedGroups(h.id),hasGenerated:q.generated(h.id).length>0,generatedNote:!q.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows:k,hasWhy:k.length>0,whyEmptyHtml:q.hasRequirements()?`No requirement claims ${X(h.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 h=Dh,H=this.ix.templates.map((q)=>{let $=this.refHtml(h,q,Rh),Z=this.refHtml(h,q,X3),z=this.ix.claims(q.id);return{linkHtml:this.link(h,q.id),kind:X(`template.${q.subType}`),description:this.description(q),payloadHtml:$!==""?$:'none',replyHtml:Z!==""?Z:'none (outbound only)',claimsHtml:z.length>0?z.map((K)=>a(K.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows:H,hasRows:H.length>0}}requirements(h,H){let q=this.ix.topRequirements.filter((Z)=>Z.kind===h),$=q.length>0?`
      ${q.map((Z)=>this.treeNode(H,Z)).join("")}
    `:"";return{isFeatures:h===i,featuresHref:X(U(H,dh)),qualitiesHref:X(U(H,ch)),featureCount:this.ix.requirements.filter((Z)=>Z.kind===i).length,qualityCount:this.ix.requirements.filter((Z)=>Z.kind===Jh).length,treeHtml:$,hasTree:q.length>0,emptyNote:h===i?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(h,H){let q=this.implLinks(H).map((z)=>{if(z.target!==void 0)return`${this.link(h,z.target,z.ref)}`;return H.status===Qh?`${X(z.ref)} (not yet)`:`${X(z.ref)} (dangling)`}),$=H.children.length>0?`${ih(this.ix.rollup(H))}`:"";return`
  • ${`
    ${r(H)}${this.reqLink(h,H)} ${a(H.status)}${_3(H)}${J3(H)}${$}${q.join("")}
    ${X(x(H.node.attrs[uh])??"")}
    `}${H.children.length>0?`
      ${H.children.map((z)=>this.treeNode(h,z)).join("")}
    `:""}
  • `}requirement(h){let H=this.ix,q=this.reqPage(h),$=[];for(let d=h;d!==void 0;d=d.parent)$.unshift(d);let Z=h.kind===i?{href:dh,label:"Features"}:{href:ch,label:"Qualities"},z=h.req.inLedger,K=h.req.diagnostics,b=this.implLinks(h),J=b.map((d)=>{let B=d.target!==void 0?H.byId.get(d.target):void 0;return{refHtml:B!==void 0?this.link(q,B.id,d.ref):`${X(d.ref)}`,kind:X(B!==void 0?`${B.type}.${B.subType}`:""),resolvesHtml:d.resolves?'resolves':h.status===Qh?'not yet (allowed on planned)':'dangling'}}),V=K.filter((d)=>d.source===Bh),W=K.filter((d)=>d.source!==Bh),y=K.some((d)=>Yq.has(d.code)),w=h.kind===i&&(h.level??0)>=P3,v=b.length===0?"none":b.every((d)=>d.resolves)?"yes":"no",l=H.below(h),k=H.slice(`requirement:${h.node.id}`),D=h;while(D!==void 0&&(D.level??0)>O3)D=D.parent;let g=o(h.node.attrs[t2]),F=this.description(h.node);return{crumbsHtml:`${Z.label} › ${$.map((d)=>d===h?X(this.reqLabel(d)):this.reqLink(q,d)).join(" › ")}`,levelHtml:r(h),name:X(this.reqLabel(h)),statusHtml:a(h.status),dispositionHtml:_3(h),verdictHtml:J3(h),address:X(`${h.req.qualifiedPath} · requirement.${h.kind}`),statement:X(x(h.node.attrs[uh])??""),counterexample:X(x(h.node.attrs[n2])??""),description:F,hasDescription:F!=="",linkRows:J,hasLinks:J.length>0,linksEmpty:h.level!==void 0&&h.levelh.children.length,hasBelow:h.children.length>0,belowBarHtml:ih(H.rollup(h)),children:h.children.map((d)=>({levelHtml:r(d),linkHtml:this.reqLink(q,d),statusHtml:a(d.status)})),sliceHref:k!==void 0?X(`${U(q,Vh)}?slice=${encodeURIComponent(k.id)}`):"",traceHref:D!==void 0?X(`${U(q,ph)}?start=${encodeURIComponent(D.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:v==="none"?'no links':v==="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:y?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:V.length>0?`${V.length}`:z?'none':'not read',how:V.length>0?V.map((d)=>`${X(d.code)} ${X(d.message)}`).join("
    "):z?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:z?`${W.length}`:'not read',how:W.length>0?W.map((d)=>`${X(d.code)} ${X(d.message)}`).join("
    "):z?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:w?'by generator':'not by default',how:w?"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((d)=>({what:X(d.what),verdictHtml:d.verdictHtml,howHtml:d.how})),trackedHtml:g.map((d)=>`${X(d)}`).join(" "),digest:X(h.req.digest)}}matrix(){let h=this.ix,H=w3,q=h.requirements.flatMap((b)=>this.implLinks(b).flatMap((J)=>J.target!==void 0?[h.ownerOf(J.target)]:[])),$=new Set([...h.storedEntities(),...h.templates.filter((b)=>h.isPrompt(b))].map((b)=>b.id));for(let b of q)if(h.byId.get(b)?.parent===void 0&&h.byId.get(b)?.type!==bh)$.add(b);let Z=[...$].map((b)=>h.byId.get(b)).sort((b,J)=>h.claims(J.id).length-h.claims(b.id).length||wh(b.name,J.name)||wh(b.id,J.id)),z=`${Z.map((b)=>`
    ${this.link(H,b.id)}
    `).join("")}`,K=[];for(let b of h.topRequirements){let J=h.subtree(b).filter((V)=>V.req.implementedBy.length>0);if(J.length===0)continue;K.push(`${b.kind===i?"Feature":"Quality"}: ${this.reqLink(H,b)}${Z.map(()=>'').join("")}`);for(let V of J){let W=new Set(this.implLinks(V).filter((w)=>w.target!==void 0).map((w)=>h.ownerOf(w.target))),y=this.reqPath(V).split(".").slice(1).join(".")||this.reqLabel(V);K.push(`${r(V)}${X(y)}${Z.map((w)=>W.has(w.id)?`${W3(V.status)}`:'').join("")}`)}}return{tableHtml:K.length>0?`${z}${K.join("")}
    `:"",hasRows:K.length>0,hasRequirements:h.hasRequirements()}}trace(){let h=this.ix.requirements.filter((q)=>q.level!==void 0&&q.level<=O3),H=h.length===0?this.ix.topRequirements:[];return{options:[...h,...H].map((q)=>({value:X(q.node.id),label:X(`${" ".repeat(Math.max(0,(q.level??1)-1))}${q.level!==void 0?`L${q.level} `:""}${this.reqLabel(q)}`)})),hasStarts:h.length+H.length>0,hasUsage:!1}}gaps(){let h=this.ix,H=sh,q=[],$=(z,K,b,J,V)=>{q.push({title:X(z),count:X(String(K)),source:X(b),isGate:b==="meta verify",whyHtml:J,bodyHtml:V})};if(h.view.sources.requirements){let z=(w)=>[...h.requirements.flatMap((v)=>v.req.diagnostics.filter((l)=>l.source===Bh===w).map((l)=>({req:v,d:l}))),...h.view.advisories.filter((v)=>v.path===""&&v.source===Bh===w).map((v)=>({d:v}))],K=(w,v)=>w.length===0?'
    None.
    ':`${w.map(({req:l,d:k})=>``).join("")}
    ${X(k.code)}${l!==void 0?this.reqLink(H,l):""}
    ${X(k.message)}
    `,b=z(!0);$("Gate findings",b.length,"meta verify","Printed by every run of the requirement gate.",K(b,(w)=>`chip v-${w==="error"?"error":"warn"}`));let J=z(!1);$("Authoring advisories",J.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",K(J,()=>"chip"));let V=h.storedEntities().filter((w)=>this.unclaimedEntity(w));$("Entities no requirement claims",V.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",V.length>0?V.map((w)=>this.link(H,w.id)).join(", "):'
    None.
    ');let W=(w)=>T2.includes(w.status),y=h.requirements.filter((w)=>W(w)&&w.node.attrs[Z3]===void 0&&!h.below(w).some(W));$("Undecided gaps",h.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.",Q3(y.map((w)=>`${r(w)}${this.reqLink(H,w)} ${a(w.status)}`)))}if(h.hasRequirements()){let z=h.requirements.filter((b)=>b.status===Qh&&h.below(b).some((J)=>J.status===Ih));$("Planned, with live work below",z.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.",Q3(z.map((b)=>`${r(b)}${this.reqLink(H,b)} ${a(b.status)} ${ih(h.rollup(b))}`)));let K=h.templates.filter((b)=>h.isPrompt(b)&&h.claims(b.id).length===0);$("Prompts no requirement claims",K.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",K.length>0?K.map((b)=>this.link(H,b.id)).join(", "):'
    None.
    ')}$("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let Z=h.storedEntities().flatMap((z)=>{let K=new Set(h.children(z.id).filter((b)=>b.type===eh&&b.attrs[U3]!==void 0).flatMap((b)=>o(b.attrs[g3])));return h.fields(z.id).filter((b)=>/[a-z]Id$/.test(b.name)&&!K.has(b.name))});if($("Fields that look like references but are not declared",Z.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.",Q3(Z.map((z)=>`${this.link(H,z.id)} ${X(z.subType)}`))),h.templates.length>0){let z=this.unusedPayload();$("Payload fields the prompt text never uses",z===void 0?"—":z.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.",z===void 0?'
    No prompt text was read.
    ':Q3(z.map(({p:K,f:b})=>`${this.link(H,K.id)}: ${this.link(H,b.id,b.name)}`)))}return{cards:q}}texts=new Map;unusedPayload(){let h=[],H=!1;for(let q of this.ix.templates){let $=this.texts.get(q.id),Z=this.refLinks(q,Rh)[0]?.id;if($===void 0||Z===void 0)continue;H=!0;let z=uH($);for(let K of this.ix.fields(Z))if(!z.has(K.name))h.push({p:q,f:K})}return H?h:void 0}api(){let h=this.ix,H=Fh,q=h.objects.filter((Z)=>h.routes(Z.id).length>0).map((Z)=>({linkHtml:this.link(H,Z.id),kind:X(h.kindOf(Z)),isReadOnly:h.storage(Z.id)?.kind==="view",routes:h.routes(Z.id).map((z)=>({method:X(z.method),methodClass:X(z.method.toLowerCase()),path:X(z.path)}))})),$=q.reduce((Z,z)=>Z+z.routes.length,0);return{groups:q,hasGroups:q.length>0,recorded:h.view.sources.routes,summary:X(`${$} route${$===1?"":"s"} on ${q.length} object${q.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((h)=>this.packageCard(vh,h))}}packageIndex(h){let H=this.ix,q=this.packagePage(h),$=[...H.objects,...H.templates,...H.others].filter((Z)=>Z.package===h).map((Z)=>{let z=H.storage(Z.id),K=H.claimStatus(Z.id);return{linkHtml:this.link(q,Z.id),kind:X(`${Z.type}.${Z.subType}`),abstractHtml:Z.abstract===!0?'abstract':"",storage:X(z===void 0?"":`${z.kind}${z.name!==void 0?` ${z.name}`:""}`),fieldCount:H.fields(Z.id).length,statusHtml:K==="unclaimed"?this.unclaimedEntity(Z)?'unclaimed':"":a(K),description:this.description(Z)}});return{name:X(h===""?"(no package)":h),crumbsHtml:`Model › ${X(h===""?"(no package)":h)}`,rows:$}}}function Q3(h){return h.length===0?'
    None.
    ':`
      ${h.map((H)=>`
    • ${H}
    • `).join("")}
    `}function Xh(h){return typeof h==="string"?h:JSON.stringify(h)}function lq(h){return h.length<=1?h[0]??"":`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`}function T3(h,H,q=`${H}s`){return`${h} ${h===1?H:q}`}function gq(h,H){if(H===1)return h;return h==="entity"?"entities":`${h}s`}var Uq=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function uH(h){let H=new Set;for(let q of h.matchAll(Uq))if(q[1]!=="/")H.add(q[2].split(".")[0]);return H}function Sq(h){let H="",q=0;for(let $ of h.matchAll(/\{\{[^}]*\}?\}\}/g))H+=X(h.slice(q,$.index)),H+=`${X($[0])}`,q=$.index+$[0].length;return H+X(h.slice(q))}var xq=[{key:"overview",label:"Overview",href:j3},{key:"map",label:"Model map",href:Vh},{key:"requirements",label:"Requirements",href:dh},{key:"matrix",label:"Matrix",href:w3},{key:"trace",label:"Trace",href:ph},{key:"prompts",label:"Prompts",href:Dh},{key:"api",label:"API",href:Fh},{key:"gaps",label:"Gaps",href:sh}];function Lq(h){if(h===void 0)return new Map;if(h instanceof Map)return h;return new Map(Object.entries(h))}function BH(h){let H=new n3(h.view),q=new E3(H),$=Lq(h.texts);for(let[y,w]of $)q.texts.set(y,w);let Z=(y)=>{let w=h.templates[y];if(w===void 0)throw Error(`docs-site explorer: no template ${y}`);return w},z=new Eh({card:Z("explorer-card.mustache")}),K=Z("explorer-head.mustache"),b=Z("explorer-foot.mustache"),J=CH(H.hasClaims()),V=new Map,W=(y,w,v,l,k,D=!1)=>{if(V.has(w))throw Error(`docs-site explorer: two pages map to ${w}`);let g=Z(y);V.set(w,()=>{let F=U(w,""),d={...k(),siteTitle:X(h.title),pageTitle:X(l),stamp:X(h.stamp??""),relRoot:F,assetBase:h.assetBase,cytoscapeSrc:h.cytoscapeSrc(F),graph3dSrc:h.graph3dSrc(F),needsGraph:D,pageKey:v,nav:xq.map((B)=>({label:B.label,href:U(w,B.href),on:B.key===v})),legendHtml:J};return v3({template:K+g+b,payload:d,provider:z,format:"text"})})};W("explorer-overview.html.mustache",j3,"overview","Overview",()=>q.overview(h.title)),W("explorer-map.html.mustache",Vh,"map","Model map",()=>q.map(),!0),W("explorer-requirements.html.mustache",dh,"requirements","Features",()=>q.requirements(i,dh)),W("explorer-requirements.html.mustache",ch,"requirements","Qualities",()=>q.requirements(Jh,ch)),W("explorer-matrix.html.mustache",w3,"matrix","Matrix",()=>q.matrix()),W("explorer-trace.html.mustache",ph,"trace","Trace",()=>q.trace(),!0),W("explorer-prompts.html.mustache",Dh,"prompts","Prompts",()=>q.prompts()),W("explorer-api.html.mustache",Fh,"api","API",()=>q.api()),W("explorer-gaps.html.mustache",sh,"gaps","Gaps",()=>q.gaps()),W("explorer-model.html.mustache",vh,"map","Packages",()=>q.model());for(let y of H.packages)W("explorer-package.html.mustache",q.packagePage(y),"map",y===""?"(no package)":y,()=>q.packageIndex(y));for(let y of H.objects)W("explorer-object.html.mustache",q.objectPage(y),"map",y.name,()=>q.object(y),!0);for(let y of H.templates)W("explorer-prompt.html.mustache",q.objectPage(y),"prompts",y.name,()=>q.prompt(y,$.get(y.id)));for(let y of H.others)W("explorer-node.html.mustache",q.objectPage(y),"map",y.name,()=>q.node(y));for(let y of H.requirements)W("explorer-requirement.html.mustache",q.reqPage(y),"requirements",q.reqLabel(y),()=>q.requirement(y));return{pages:V,graphData:()=>Nq(H,q)}}function Nq(h,H){let q=h.features(),$=[...h.objects,...h.templates],Z=$.map((W)=>{let y=h.featureOf(W.id),w=h.claims(W.id);return{id:W.id,name:W.name,kind:h.kindOf(W),pkg:W.package,href:H.objectPage(W),abstract:W.abstract===!0?1:0,fields:h.fields(W.id).length,claims:w.length,status:h.claimStatus(W.id),feature:y!==void 0?q.indexOf(y):-1,quality:w.length>0&&w.every((v)=>v.req.kind===Jh)?1:0,unclaimed:H.unclaimedEntity(W)?1:0,api:h.routes(W.id).map((v)=>`${v.method} ${v.path}`),gen:h.generated(W.id).length,storage:h.storage(W.id)?.kind??""}}),z=new Set($.map((W)=>W.id)),K={};for(let W of h.view.slices)K[W.id]=[...new Set(W.nodes.map((y)=>h.ownerOf(y)).filter((y)=>z.has(y)))].sort();let b=h.requirements.map((W)=>({id:W.node.id,label:H.reqLabel(W),path:H.reqPath(W),level:W.level??0,status:W.status,kind:W.kind,parent:W.parent?.node.id??"",href:H.reqPage(W),targets:h.linkTargets(W).map((y)=>h.ownerOf(y)),statement:W.req.statement,rollup:h.rollup(W),claimed:h.targetsOf(W).length})),J={};for(let W of $){let y=new Map;for(let w of h.generated(W.id))y.set(w.generatedBy,(y.get(w.generatedBy)??0)+1);if(y.size>0)J[W.id]=[...y.entries()].sort((w,v)=>w[0]v[0]?1:0)}let V=[];for(let W of $){let y=typeof W.attrs[Wh]==="string"?W.attrs[Wh]:"";V.push({t:W.name,s:`${W.type}.${W.subType}${W.package!==""?` · ${W.package}`:""}`,h:H.objectPage(W),k:`${W.name} ${W.id} ${y}`.toLowerCase()});for(let w of h.fields(W.id)){if(w.inheritedFrom!==void 0)continue;V.push({t:`${W.name}.${w.name}`,s:`field.${w.subType}`,h:H.pageOf(w.id)??H.objectPage(W),k:`${W.name}.${w.name} ${w.id}`.toLowerCase()})}}for(let W of h.others){let y=typeof W.attrs[Wh]==="string"?W.attrs[Wh]:"";V.push({t:W.name,s:`${W.type}.${W.subType}${W.package!==""?` · ${W.package}`:""}`,h:H.objectPage(W),k:`${W.name} ${W.id} ${y}`.toLowerCase()})}for(let W of h.requirements)V.push({t:H.reqLabel(W),s:`${W.level!==void 0?`L${W.level}`:"—"} ${W.kind}${W.status!==""?` · ${W.status}`:""} · ${H.reqPath(W)}`,h:H.reqPage(W),k:`${H.reqPath(W)} ${W.node.id} ${H.reqLabel(W)} ${W.req.statement}`.toLowerCase()});return{nodes:Z,edges:h.modelEdges().filter((W)=>z.has(W.from)&&z.has(W.to)).map((W)=>({s:W.from,t:W.to,k:W.kind,...W.via!==void 0?{v:fq(W.via)}:{}})),slices:K,features:q.map((W)=>({id:W.node.id,label:H.reqLabel(W)})),reqs:b,generated:J,search:V,hasClaims:h.hasClaims(),requirementType:bh}}function fq(h){let H=h.lastIndexOf(".");return H<0?h:h.slice(H+1)}function vH(h){return BH({view:h.view,title:h.title,templates:{...V3,...h.templates},texts:h.texts,...h.footer!==""&&{stamp:h.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor:vH,templates:V3};if(typeof document<"u")Oq(window);function Oq(h){let $,Z="",z={path:"",search:""},K=[],b=(C)=>{let Y=C.replace(/^#\/?/,""),j=new URL(Y===""?"index.html":Y,"http://explorer.invalid/"),Q=j.pathname.slice(1);try{Q=decodeURIComponent(Q)}catch{}return{path:Q===""?"index.html":Q,search:j.search,anchor:j.hash.slice(1)}},J=(C,Y,j="")=>`#/${C}${Y}${j!==""?`#${j}`:""}`;h.MO_APP={href:(C)=>{let Y=b(C);return J(Y.path,Y.search,Y.anchor)},search:()=>z.search,replaceQuery:(C)=>{z={path:z.path,search:C==="?"?"":C},history.replaceState(null,"",J(z.path,z.search))},listen:(C,Y)=>{document.addEventListener(C,Y),K.push(()=>document.removeEventListener(C,Y))},onLeave:(C)=>{K.push(C)}};let V=(C=h.MO_MODEL)=>{if(C===void 0)return!1;return $=vH(C),h.MO_EXPLORER=$.graphData(),Z=C.stamp,!0},y=new URLSearchParams(location.search).get("source"),w,v;if(y!==null&&y!=="")try{w=new URL(y,location.href)}catch{}let l=()=>{if(y===null||y==="")return;let C=v?.ok??!1,Y=r3(w?.href??y),j=C?`● Following the running application at ${Y}`:`● Cannot read ${Y}${v!==void 0&&v.error!==""?` (${r3(v.error)})`:""}${$!==void 0?", showing the model it last served":""}; trying again every second`,Q=document.getElementById("mo-live");if(Q===null)Q=document.createElement("div"),Q.id="mo-live",document.body.appendChild(Q);if(Q.innerHTML!==j)Q.innerHTML=j;let m=C?"live-source":"live-source down";if(Q.className!==m)Q.className=m;if(v!==void 0)Q.dataset.checked=new Date(v.at).toISOString();document.documentElement.setAttribute("data-mo-source",C?"live":"down")},k=(C,Y,j)=>{for(let Q of Array.from(C.querySelectorAll("a[href]"))){let m=Q.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(m))continue;if(m.startsWith("#")){Q.setAttribute("href",J(Y,j,m.slice(1)));continue}let G=new URL(m,"http://explorer.invalid/"+Y);Q.setAttribute("href",J(G.pathname.slice(1),G.search,G.hash.slice(1)))}},D=(C)=>{let Y=b(location.hash),j=$?.pages.get(Y.path);for(let u of K)u();K=[],z={path:Y.path,search:Y.search};let Q=j!==void 0?j():`Not found

    No such page

    ${r3(Y.path)} is not a page of this model.

    Overview

    `,m=new DOMParser().parseFromString(Q,"text/html");m.querySelectorAll("script").forEach((u)=>u.remove()),k(m,Y.path,Y.search);let G=window.scrollY;document.title=m.title;for(let u of Array.from(document.body.attributes))document.body.removeAttribute(u.name);for(let u of Array.from(m.body.attributes))document.body.setAttribute(u.name,u.value);if(document.body.replaceChildren(...Array.from(m.body.childNodes).map((u)=>document.importNode(u,!0))),j!==void 0)h.MO_THEME?.();if(C)window.scrollTo(0,G);else if(Y.anchor!=="")document.getElementById(Y.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",Y.path),l()};window.addEventListener("hashchange",()=>{let C=b(location.hash);if(C.path===z.path&&C.search===z.search){if(C.anchor!=="")document.getElementById(C.anchor)?.scrollIntoView();return}D(!1)});let g=(C,Y)=>{let j=document.createElement("script");j.src=`${C}?t=${Date.now()}`,j.onload=()=>{j.remove(),Y()},j.onerror=()=>{j.remove(),Y()},document.head.appendChild(j)},F=()=>{g("explorer-stamp.js",()=>{if(h.MO_STAMP===void 0||h.MO_STAMP===Z)return void setTimeout(F,1000);let C=h.MO_STAMP;g("explorer-model.js",()=>{if(h.MO_MODEL?.stamp===C&&V())D(!0);setTimeout(F,1000)})})},d=(C)=>{let Y="",j=async()=>{try{let Q=await fetch(C.href,{cache:"no-cache"});if(!Q.ok)throw Error(`HTTP ${Q.status}`);let m=await Q.text();if(m!==Y){let G=JSON.parse(m);if(typeof G!=="object"||G===null||!String(G.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let u=h.MO_MODEL,M=$===void 0;V({stamp:Q.headers.get("etag")??`${m.length}`,title:u?.title??C.host,footer:u?.footer??"",texts:u?.texts??{},templates:u?.templates??{},view:G}),Y=m,v={ok:!0,at:Date.now(),error:""},D(!M)}else v={ok:!0,at:Date.now(),error:""},l()}catch(Q){if(v={ok:!1,at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},$===void 0)document.body.innerHTML="

    No model yet

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

    ";l()}setTimeout(()=>void j(),1000)};j()},B=()=>{if(y!==null&&y!==""){if(w===void 0){v={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",l();return}d(w);return}if(!V())document.body.innerHTML="

    No model

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

    ";else D(!1);setTimeout(F,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",B);else B()}function r3(h){return h.replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H])}})(); + */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/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js b/server/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js index 3a52a6d4e0..dd2a04d098 100644 --- a/server/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js +++ b/server/python/src/metaobjects/documentation/explorer_app/assets/explorer-app.js @@ -11,7 +11,7 @@ * * 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. */ -(()=>{var V3={"explorer-head.mustache":` +(()=>{var explorer_templates_default={"explorer-head.mustache":` @@ -260,10 +260,10 @@ `};/*! * mustache.js - Logic-less {{mustache}} templates with JavaScript * http://github.com/janl/mustache.js - */var DH=Object.prototype.toString,Gh=Array.isArray||function(H){return DH.call(H)==="[object Array]"};function m3(h){return typeof h==="function"}function FH(h){return Gh(h)?"array":typeof h}function d3(h){return h.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function o3(h,H){return h!=null&&typeof h==="object"&&H in h}function YH(h,H){return h!=null&&typeof h!=="object"&&h.hasOwnProperty&&h.hasOwnProperty(H)}var MH=RegExp.prototype.test;function kH(h,H){return MH.call(h,H)}var lH=/\S/;function gH(h){return!kH(lH,h)}var UH={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function SH(h){return String(h).replace(/[&<>"'`=\/]/g,function(q){return UH[q]})}var xH=/\s*/,LH=/\s+/,e3=/\s*=/,NH=/\s*\}/,fH=/#|\^|\/|>|\{|&|=|!/;function OH(h,H){if(!h)return[];var q=!1,$=[],Z=[],z=[],K=!1,b=!1,J="",V=0;function W(){if(K&&!b)while(z.length)delete Z[z.pop()];else z=[];K=!1,b=!1}var y,w,v;function l(Q){if(typeof Q==="string")Q=Q.split(LH,2);if(!Gh(Q)||Q.length!==2)throw Error("Invalid tags: "+Q);y=new RegExp(d3(Q[0])+"\\s*"),w=new RegExp("\\s*"+d3(Q[1])),v=new RegExp("\\s*"+d3("}"+Q[1]))}l(H||p.tags);var k=new Mh(h),D,g,F,d,B,C;while(!k.eos()){if(D=k.pos,F=k.scanUntil(y),F)for(var Y=0,j=F.length;Y")B=[g,F,D,k.pos,J,V,q];else B=[g,F,D,k.pos];if(V++,Z.push(B),g==="#"||g==="^")$.push(B);else if(g==="/"){if(C=$.pop(),!C)throw Error('Unopened section "'+F+'" at '+D);if(C[1]!==F)throw Error('Unclosed section "'+C[1]+'" at '+D)}else if(g==="name"||g==="{"||g==="&")b=!0;else if(g==="=")l(F)}if(W(),C=$.pop(),C)throw Error('Unclosed section "'+C[1]+'" at '+k.pos);return AH(PH(Z))}function PH(h){var H=[],q,$;for(var Z=0,z=h.length;Z0?$[$.length-1][4]:H;break;default:q.push(Z)}return H}function Mh(h){this.string=h,this.tail=h,this.pos=0}Mh.prototype.eos=function(){return this.tail===""};Mh.prototype.scan=function(H){var q=this.tail.match(H);if(!q||q.index!==0)return"";var $=q[0];return this.tail=this.tail.substring($.length),this.pos+=$.length,$};Mh.prototype.scanUntil=function(H){var q=this.tail.search(H),$;switch(q){case-1:$=this.tail,this.tail="";break;case 0:$="";break;default:$=this.tail.substring(0,q),this.tail=this.tail.substring(q)}return this.pos+=$.length,$};function yh(h,H){this.view=h,this.cache={".":this.view},this.parent=H}yh.prototype.push=function(H){return new yh(H,this)};yh.prototype.lookup=function(H){var q=this.cache,$;if(q.hasOwnProperty(H))$=q[H];else{var Z=this,z,K,b,J=!1;while(Z){if(H.indexOf(".")>0){z=Z.view,K=H.split("."),b=0;while(z!=null&&b")V=this.renderPartial(b,q,$,z);else if(J==="&")V=this.unescapedValue(b,q);else if(J==="name")V=this.escapedValue(b,q,z);else if(J==="text")V=this.rawValue(b);if(V!==void 0)K+=V}return K};O.prototype.renderSection=function(H,q,$,Z,z){var K=this,b="",J=q.lookup(H[1]);function V(w){return K.render(w,q,$,z)}if(!J)return;if(Gh(J))for(var W=0,y=J.length;W0||!$))z[K]=Z+z[K];return z.join(` -`)};O.prototype.renderPartial=function(H,q,$,Z){if(!$)return;var z=this.getConfigTags(Z),K=m3($)?$(H[1]):$[H[1]];if(K!=null){var b=H[6],J=H[5],V=H[4],W=K;if(J==0&&V)W=this.indentPartial(K,V,b);var y=this.parse(W,z);return this.renderTokens(y,q,$,W,Z)}};O.prototype.unescapedValue=function(H,q){var $=q.lookup(H[1]);if($!=null)return $};O.prototype.escapedValue=function(H,q,$){var Z=this.getConfigEscape($)||p.escape,z=q.lookup(H[1]);if(z!=null)return typeof z==="number"&&Z===p.escape?String(z):Z(z)};O.prototype.rawValue=function(H){return H[1]};O.prototype.getConfigTags=function(H){if(Gh(H))return H;else if(H&&typeof H==="object")return H.tags;else return};O.prototype.getConfigEscape=function(H){if(H&&typeof H==="object"&&!Gh(H))return H.escape;else return};var p={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(h){Yh.templateCache=h},get templateCache(){return Yh.templateCache}},Yh=new O;p.clearCache=function(){return Yh.clearCache()};p.parse=function(H,q){return Yh.parse(H,q)};p.render=function(H,q,$,Z){if(typeof H!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+FH(H)+'" was given as the first argument for mustache#render(template, view, partials)');return Yh.render(H,q,$,Z)};p.escape=SH;p.Scanner=Mh;p.Context=yh;p.Writer=O;var Hh=p;var y3=(h)=>h.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),IH=/^-?[0-9]+(\.[0-9]+)?$/,H2=(h)=>/^[=+\-@\t\r]/.test(h)&&!IH.test(h)?"'"+h:h,RH=(h)=>{let H=H2(h);return/[",\n\r]/.test(H)?`"${H.replace(/"/g,'""')}"`:H},iH=(h)=>JSON.stringify(h).slice(1,-1),h2=(h)=>h,q2={text:h2,markdown:h2,html:y3,xml:y3,json:iH,csv:RH,spreadsheet:(h)=>H2(y3(h))};var $2="has";function ah(h){return"has"+cH(h)}var kh="-last";function cH(h){if(h.length===0)return h;let H=h.charAt(0);if(H===H.toUpperCase()&&H!==H.toLowerCase())return h;return H.toUpperCase()+h.slice(1)}function Z2(h){if(h===null||h===void 0)return!1;if(typeof h==="string")return h.trim().length>0;if(Array.isArray(h))return h.length>0;if(typeof h==="number"||typeof h==="boolean"||typeof h==="bigint")return;return typeof h==="object"}function z2(h,H=0){return lh(h,H,void 0)}function lh(h,H,q){if(H>32)return h;if(Array.isArray(h)){let K=h.length-1;return h.map((b,J)=>lh(b,H+1,J===K))}if(h===null||typeof h!=="object")return h;let $=Object.getPrototypeOf(h);if($!==Object.prototype&&$!==null)return sH(h,H,q);let Z=h,z={};for(let[K,b]of Object.entries(Z))z[K]=lh(b,H+1,void 0);for(let[K,b]of Object.entries(Z)){let J=ah(K);if(Object.prototype.hasOwnProperty.call(Z,J))continue;let V=Z2(b);if(V!==void 0)z[J]=V}if(q!==void 0&&!Object.prototype.hasOwnProperty.call(Z,kh))z[kh]=q;return z}function pH(h){return h.length===0?h:h.charAt(0).toLowerCase()+h.slice(1)}function sH(h,H,q){let $=new Map,Z=(K)=>{if($.has(K))return $.get(K);let b=Reflect.get(h,K,h),J=typeof b==="function"?(...V)=>lh(Reflect.apply(b,h,V),H+1,void 0):lh(b,H+1,void 0);return $.set(K,J),J},z=(K)=>{if(typeof K!=="string")return;if(K===kh)return q;if(!K.startsWith("has"))return;let b=K.slice(3);for(let J of[pH(b),b]){if(!(J in h)||ah(J)!==K)continue;let V=Reflect.get(h,J,h);if(typeof V==="function")continue;let W=Z2(V);if(W!==void 0)return W}return};return new Proxy(Object.create(null),{has:(K,b)=>(b in h)||z(b)!==void 0,get:(K,b)=>(b in h)?Z(b):z(b)})}var b2=["mustache","jinja"],gh="mustache",e="jinja";var K2=[".jinja",".j2",".jinja2"];function qh(h,H,q){let $=h.engineOf?.(H);return $!==void 0&&$!==q}function th(h,H){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${h} is not a ${H} template; a ${H} body includes only ${H} partials`}function X2(h,H,q){if(q!==void 0){if(!b2.includes(q))throw Error(`unknown template engine ${JSON.stringify(q)}; expected one of ${b2.join(", ")}`);return q}if(h!==void 0&&H!==void 0){let $=h.engineOf?.(H);if($!==void 0)return $}return"mustache"}var R="ERR_VAR_NOT_ON_PAYLOAD",Uh="ERR_PARTIAL_UNRESOLVED",G3="ERR_REQUIRED_SLOT_UNUSED";var Sh="ERR_TEMPLATE_NOT_STATIC",$h="ERR_TEMPLATE_SYNTAX",xh="ERR_TEMPLATE_ENGINE_UNSUPPORTED",t=32,aH=new Set([">"," ","\t",` -`,"\r"]);function tH(h,H){let q=`<${H}`;for(let $=h.indexOf(q);$!==-1;$=h.indexOf(q,$+1)){let Z=h[$+q.length];if(Z!==void 0&&aH.has(Z))return!0}return!1}function nH(h,H){return h.includes(``)}function nh(h,H,q){let $=[];for(let z of q?.requiredSlots??[])if(!h.has(z))$.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:z});let Z=q?.requiredTags??[];if(Z.length>0){let z=H.join(` -`);for(let K of Z)if(!tH(z,K)||!nH(z,K))$.push({code:"ERR_OUTPUT_TAG_MISSING",path:K})}return $}var _H=()=>{throw Error("the explorer app renders Mustache only")},C3=new Proxy({},{get:()=>_H});var Zh=C3;function Lh(h){return Zh.parser.parse(h)}function zh(h){return typeof h==="object"&&h!==null&&typeof h.typename==="string"}function I(h){let H=[],q=($)=>{if(Array.isArray($))$.forEach(q);else if(zh($))H.push($)};for(let $ of h.fields)q(h[$]);if(h.typename==="Set")q(h.body);return H}function Nh(h){for(let H of K2)if(h.toLowerCase().endsWith(H))return h.slice(0,-H.length);return h}function TH(h){return function(H,q){this._emit("runtime.markSafe("),h.call(this,H,q),this._emit(")")}}function EH(h){let H={getSource(q){let $=h.resolve(Nh(q));return $===void 0?null:{src:$,path:q,noCache:!0}}};return new C3.Environment(H,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function rH(h){if(h===void 0)throw Error(`render verify failed: ${R}`);return h}function W2(h,H,q,$){let Z=EH(q),z=Zh.compiler.Compiler.prototype,K=Zh.lib.escape,b=z.compileCapture,J=Zh.runtime.ensureDefined;Zh.runtime.ensureDefined=rH,Zh.lib.escape=(V)=>$(typeof V==="string"?V:String(V)),z.compileCapture=TH(b);try{return Z.renderString(h,H)}finally{Zh.lib.escape=K,z.compileCapture=b,Zh.runtime.ensureDefined=J}}var S={tag:"opaque"},oH=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),eH=new Set(["first","last","random"]),hq=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),Hq=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),qq="attribute";function J2(h,H){return{tag:"typed",fields:h.fields,isArray:h.isArray===!0,path:H}}function Q2(h,H){if(h.tag==="opaque")return S;return{tag:"typed",fields:h.isArray?h.fields:void 0,isArray:!1,path:H}}function u3(h){if(h.kind==="key")return`.${h.key}`;if(h.kind==="index")return`[${h.index}]`;return"[*]"}function j2(h,H,q){let $=[],Z=q?.provider,z=new Set,K=[h],b=(j,Q)=>{$.push({code:j,path:Q})};function J(j,Q){for(let G=Q.frames.length-1;G>=0;G--){let u=Q.frames[G].get(j);if(u!==void 0)return u}let m=Q.root.find((G)=>G.name===j);if(m!==void 0){if(Q.root===H)z.add(j);return J2(m,j)}return oH.has(j)?S:void 0}function V(j,Q,m){j.frames[j.frames.length-1].set(Q,m)}function W(j){return{...j,frames:[...j.frames,new Map]}}function y(j){let Q=[],m=j;while(m.typename==="LookupVal"){let G=m.val;if(G.typename==="Literal"&&typeof G.value==="string")Q.unshift({kind:"key",key:G.value});else if(G.typename==="Literal"&&typeof G.value==="number")Q.unshift({kind:"index",index:G.value});else Q.unshift({kind:"dynamic",node:G});m=m.target}return{base:m,segments:Q}}function w(j,Q){let{base:m,segments:G}=y(j);for(let L of G)if(L.kind==="dynamic")B(L.node,Q);let u,M;if(m.typename==="Symbol"){M=m.value;let L=M+G.map(u3).join(""),c=J(M,Q);if(c===void 0)return b(R,L),S;u=c}else u=B(m,Q),M=u.tag==="typed"?u.path:"";let s=M+G.map(u3).join("");for(let L of G){if(u.tag==="opaque")return S;if(M+=u3(L),L.kind==="key"){let c=u.isArray?void 0:u.fields?.find((mh)=>mh.name===L.key);if(c===void 0)return b(R,s),S;u=J2(c,M)}else if(u.isArray)u={tag:"typed",fields:u.fields,isArray:!1,path:M};else if(L.kind==="dynamic"&&u.fields!==void 0)return b(Sh,s),S;else u={tag:"typed",fields:u.fields,isArray:!1,path:M}}return u}function v(j,Q,m){if(j.tag==="opaque"){B(Q,m);return}if(Q.typename!=="Literal"||typeof Q.value!=="string"){B(Q,m),b(Sh,`${j.path}[*]`);return}let G=Q.value,u=j.fields;for(let M of G.split(".")){let s=u?.find((L)=>L.name===M);if(s===void 0){b(R,`${j.path}.${G}`);return}u=s.fields}}function l(j){let Q=[],m=[];for(let G of j===void 0?[]:I(j))if(G.typename==="KeywordArgs")for(let u of I(G)){let M=u.key;m.push([String(M.value),u.value])}else Q.push(G);return{positional:Q,keywords:m}}function k(j,Q){let m=String(j.name.value),{positional:G,keywords:u}=l(j.args),[M,...s]=G,L=M===void 0?S:B(M,Q);s.forEach((c,mh)=>{if(mh===Hq.get(m))v(L,c,Q);else B(c,Q)});for(let[c,mh]of u)if(c===qq)v(L,mh,Q);else B(mh,Q);if(eH.has(m))return L.tag==="typed"?Q2(L,`${L.path}|${m}`):S;if(hq.has(m))return L;return S}function D(j,Q){let m=j.name;if(m.typename==="LookupVal")B(m.target,Q);else if(m.typename==="Symbol"){let M=m.value;if(J(M,Q)===void 0)b(R,M)}else B(m,Q);let{positional:G,keywords:u}=l(j.args);return G.forEach((M)=>B(M,Q)),u.forEach(([,M])=>B(M,Q)),S}function g(j,Q){let m=W(Q);for(let G of["caller","varargs","kwargs"])V(m,G,S);for(let G of I(j.args))if(G.typename==="Symbol")V(m,G.value,S);else if(G.typename==="KeywordArgs")for(let u of I(G))B(u.value,Q),V(m,String(u.key.value),S);C(j.body,m)}function F(j,Q,m,G,u=!1){if(Q.typename!=="Literal"||typeof Q.value!=="string"){B(Q,m),b(Sh,j);return}if(Z===void 0)return;let M=Nh(Q.value);if(m.seen.includes(M)||m.seen.length>=t)return;let s=Z.resolve(M);if(s===void 0){if(!u)b(Uh,M);return}if(qh(Z,M,e)){b(xh,M);return}K.push(s);let L;try{L=Lh(s)}catch(c){b($h,`${M}: ${c.message}`);return}C(L,G(m,M))}function d(j,Q,m){if(j.typename==="Symbol")V(m,j.value,Q);else for(let G of I(j))d(G,S,m)}function B(j,Q){switch(j.typename){case"Symbol":case"LookupVal":return w(j,Q);case"Literal":case"TemplateData":return S;case"Group":{let m=I(j);if(m.length===1)return B(m[0],Q);return m.forEach((G)=>B(G,Q)),S}case"Filter":case"FilterAsync":return k(j,Q);case"FunCall":return D(j,Q);case"Caller":return g(j,Q),S;case"Is":{B(j.left,Q);let m=j.right;if(m.typename==="FunCall"){let{positional:G,keywords:u}=l(m.args);G.forEach((M)=>B(M,Q)),u.forEach(([,M])=>B(M,Q))}return S}case"Pair":{let m=j.key;if(m.typename!=="Symbol")B(m,Q);return B(j.value,Q),S}case"Capture":return C(j.body,Q),S;default:for(let m of I(j))B(m,Q);return S}}function C(j,Q){switch(j.typename){case"Root":case"NodeList":for(let m of I(j))C(m,Q);return;case"Output":for(let m of I(j))B(m,Q);return;case"If":case"IfAsync":{if(B(j.cond,Q),C(j.body,Q),zh(j.else_))C(j.else_,Q);return}case"For":case"AsyncEach":case"AsyncAll":{let m=B(j.arr,Q),G=W(Q);V(G,"loop",S);let u=j.name;if(u.typename==="Symbol"){let M=u.value;V(G,M,Q2(m,M))}else d(u,S,G);if(C(j.body,G),zh(j.else_))C(j.else_,Q);return}case"Set":{let m=j.targets.filter(zh),G=S;if(zh(j.value))G=B(j.value,Q);else if(zh(j.body))B(j.body,Q);for(let u of m){let M=u.value;V(Q,M,G.tag==="typed"&&m.length===1?{...G,path:M}:S)}return}case"Macro":V(Q,String(j.name.value),S),g(j,Q);return;case"Include":F("include",j.template,Q,(m,G)=>({...W(m),seen:[...m.seen,G]}),j.ignoreMissing===!0);return;case"Import":case"FromImport":{let m=j.withContext===!0;if(F("import",j.template,Q,(G,u)=>({frames:[new Map],root:m?H:[],seen:[...G.seen,u]})),j.typename==="Import")V(Q,String(j.target.value),S);else for(let G of I(j.names)){let u=G.typename==="Pair"?G.value:G;V(Q,String(u.value),S)}return}case"Extends":F("extends",j.template,Q,(m,G)=>({frames:[new Map],root:H,seen:[...m.seen,G]}));return;case"Block":C(j.body,Q);return;case"Switch":{B(j.expr,Q);for(let m of I(j.cases))B(m.cond,Q),C(m.body,Q);if(zh(j.default))C(j.default,Q);return}default:B(j,Q)}}let Y;try{Y=Lh(h)}catch(j){return[{code:$h,path:j.message}]}return C(Y,{frames:[new Map],root:H,seen:[]}),$.push(...nh(z,K,q)),$}function w2(h,H){if(H.includes("."))return!1;if(!H.startsWith($2))return!1;for(let q=h.length-1;q>=0;q--)for(let $ of h[q])if(H===ah($.name))return!0;return!1}function V2(h,H){return h&&H===kh}function d2(h,H){return h.find((q)=>q.name===H)}function $q(h,H){let q=H.split("."),$;for(let Z=h.length-1;Z>=0;Z--){let z=d2(h[Z],q[0]);if(z){$=z;break}}for(let Z=1;$&&ZH[0]===Zq).map((H)=>[H[1],H[2],H[3]])}function Kq(h){return Th(h).some((H)=>H[0]===bq)}function _h(h,H){if(!Kq(h))return;return H??B3(h)[0]?.[0]}function Xq(h){return Th(h).filter((H)=>H[0]===zq).map((H)=>[H[2],H[3]])}function G2(h,H){let q="",$=0;for(let[Z,z]of Xq(H))q+=h.slice($,Z),$=z;return q+h.slice($)}function Wq(h){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(h instanceof Error?h.message:"")?.[1]}function u2(h){return C2(h)}function B2(h,H,q){if(q?.engine===e)return j2(h,H,q);let $=[],Z=q?.provider,z=H,K=new Set,b=[h];function J(y,w,v,l=!1){let k=w.length===1&&w[0]===z;for(let D of y){let g=D[0],F=D[1];switch(g){case"name":case"&":case"{":{if(F===".")break;if(k)K.add(F.split(".")[0]);if(!m2(w,F)&&!w2(w,F)&&!V2(l,F))$.push({code:R,path:F});break}case"#":case"^":{let d=Array.isArray(D[4])?D[4]:[];if(F==="."){J(d,w,v,l);break}if(k)K.add(F.split(".")[0]);let B=m2(w,F);if(!B){if(V2(l,F)){J(d,w,v,l);break}if(w2(w,F)){J(d,w,v,l);break}$.push({code:R,path:F});break}let C=g==="#"&&B.fields!==void 0,Y=g==="#"&&B.isArray===!0;J(d,C?[...w,B.fields]:w,v,Y?B.fields!==void 0:l);break}case">":{if(!Z)break;if(v.includes(F)||v.length>=t)break;let d=Z.resolve(F);if(d===void 0){$.push({code:Uh,path:F});break}if(qh(Z,F,gh)){$.push({code:xh,path:F});break}let B=y2(d);if(!Array.isArray(B)){$.push(B);break}let C=_h(B,F);if(C!==void 0)$.push({code:$h,path:C});b.push(G2(d,B)),J(B,w,[...v,F],l);break}default:break}}}let V=y2(h);if(!Array.isArray(V))return[V];let W=_h(V,void 0);if(W!==void 0)$.push({code:$h,path:W});return b[0]=G2(h,V),J(V,[z],[]),$.push(...nh(K,b,q)),$}var Jq=new Set(["Include","Import","FromImport","Extends"]);function v2(h,H){if(Jq.has(h.typename)){let q=h.template;if(q.typename==="Literal"&&typeof q.value==="string")H.push({ref:Nh(q.value),optional:h.ignoreMissing===!0})}for(let q of I(h))v2(q,H)}function D2(h,H,q){let $=[];v2(Lh(h),$);for(let{ref:Z,optional:z}of $){if(q.includes(Z))throw Error(`partial cycle: ${[...q,Z].join(" -> ")}`);if(q.length>=t)throw Error(`partial depth exceeded ${t}: ${Z}`);let K=H.resolve(Z);if(K===void 0){if(z)continue;throw Error(`unresolved partial: ${Z}`)}if(qh(H,Z,e))throw Error(th(Z,e));D2(K,H,[...q,Z])}}function F2(h,H,q,$,Z){return D2(h,$,H!==void 0?[H]:[]),W2(h,typeof q==="object"&&q!==null?q:{},$,Z)}function Y2(h,H,q,$){let Z=u2(h);if(_h(Z,$)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let z=B3(Z);if(z.length===0)return h;let K="",b=0;for(let[J,V,W]of z){if(q.includes(J))throw Error(`partial cycle: ${[...q,J].join(" -> ")}`);if(q.length>=t)throw Error(`partial depth exceeded ${t}: ${J}`);let y=H.resolve(J);if(y===void 0)throw Error(`unresolved partial: ${J}`);if(qh(H,J,gh))throw Error(th(J,gh));K+=h.slice(b,V)+Y2(y,H,[...q,J],J),b=W}return K+h.slice(b)}function v3(h){let H=h.template??(h.ref!==void 0?h.provider.resolve(h.ref):void 0);if(H===void 0)throw Error(`unresolved ref: ${h.ref??"(none)"}`);let q=X2(h.provider,h.template===void 0?h.ref:void 0,h.engine);if(h.verify!==void 0){let z=B2(H,h.verify,{provider:h.provider,engine:q}).filter((K)=>K.code!==G3);if(z.length>0)throw Error(`render verify failed: ${z.map((K)=>`${K.code} (${K.path})`).join(", ")}`)}let $=q2[h.format??"text"],Z=q===e?F2(H,h.template===void 0?h.ref:void 0,h.payload,h.provider,$):jq(H,h,$);if(h.maxChars!==void 0&&Z.length>h.maxChars)throw Error(`render exceeded maxChars budget: ${Z.length} > ${h.maxChars}`);return Z}function Qq(){let h=Hh.Writer.prototype,H={escapedValue:h.escapedValue,unescapedValue:h.unescapedValue};for(let q of["escapedValue","unescapedValue"]){let $=H[q];h[q]=function(Z,z,...K){let b=String(Z[1]);if(z.lookup(b)===void 0)throw Error(`render verify failed: ${R} (${b})`);return $.call(this,Z,z,...K)}}return()=>{h.escapedValue=H.escapedValue,h.unescapedValue=H.unescapedValue}}function jq(h,H,q){let $=Y2(h,H.provider,H.ref!==void 0?[H.ref]:[]),Z=Hh.escape;Hh.escape=(b)=>q(typeof b==="string"?b:String(b));let z,K=Qq();try{z=Hh.render($,z2(H.payload),{})}finally{Hh.escape=Z,K()}return z}class Eh{map;engine;constructor(h,H={}){this.map=h;this.engine=H.engine}resolve(h){return Object.prototype.hasOwnProperty.call(this.map,h)?this.map[h]:void 0}engineOf(h){return this.resolve(h)===void 0?void 0:this.engine}}var rh="object",oh="field";var eh="identity",h3="relationship",M2="layout",k2="source",D3="origin",H3="template",F3="index",bh="requirement",fh="dimension",Oh="measure",Ph="segment";var Wh="description",l2="summary";var Ch="string";var g2="currency",Ah="enum",U2="uuid",S2="uri",x2="inet",L2="duration";var Y3="required";var M3="default",k3="maxLength";var N2="filterable",f2="sortable";var q3="objectRef";var l3="values";var g3="fields";var U3="references";var S3="entity",O2="value",P2="projection",A2="report";var $3="from",I2="dimensions",R2="measures",i2="segment",x3="filter",c2="spine";var N="eq",P="ne",n="gt",_="gte",T="lt",E="lte",A="in",L3="like",f="isNull";var R1={string:[N,P,A,L3,f],[Ah]:[N,P,A,L3,f],int:[N,P,n,_,T,E,A,f],long:[N,P,n,_,T,E,A,f],double:[N,P,n,_,T,E,A,f],float:[N,P,n,_,T,E,A,f],decimal:[N,P,n,_,T,E,A,f],[g2]:[N,P,n,_,T,E,A,f],boolean:[N,f],date:[N,P,n,_,T,E,A,f],time:[N,P,n,_,T,E,A,f],timestamp:[N,P,n,_,T,E,A,f],[U2]:[N,P,A,f],[S2]:[N,P,A,L3,f],[x2]:[N,P,A,f],[L2]:[N,P,n,_,T,E,A,f]};var wq="association",Vq="aggregation",dq="composition";var p2="cardinality",s2="objectRef",a2="through";var p1={[dq]:"cascade",[Vq]:"set-null",[wq]:"restrict"};var i="functional",Jh="architectural";var Z3="disposition",t2="trackedBy",uh="statement",n2="counterexample";var Qh="planned",Ih="live",N3="partial",f3="retired",_2=["planned","live","partial","retired"];var T2=["planned","partial"];var O3=3,P3=4;var z3="from";var E2="agg",b3="of",A3="via",I3="filter";var R3="expr";var mq=["count","sum","avg","min","max"];var r2="any",o2="all",yq="collect",E1=[...mq,r2,o2,yq];var e2="of",hH="via",HH="grains",qH="agg";var i3="filter",$H="segment",ZH="numerator",zH="denominator";var c3="default";var bH="column";var Gq="uuid",Cq="jsonb";var uq="text",Bq="varchar",vq="character varying";var Z5={[Gq]:[Ch],[Cq]:[Ch],[uq]:[Ch],[Bq]:[Ch],[vq]:[Ch]};var KH="table",XH="view";var WH="kind";var JH="view";var p3="pageSize",QH="defaultSortField",s3="defaultSortOrder";var jH="columns";var a3="prompt";var Rh="payloadRef",wH="textRef",K3="format";var X3="responseRef",VH="maxTokens";var dH="model";var mH="promptStyle";var yH="responseFormat";var jh=[Ih,N3,Qh,f3].filter((h)=>_2.includes(h)),t3={[Ih]:"●",[N3]:"◐",[Qh]:"○",[f3]:"⊘"},GH=(h,H)=>hH?1:0;class n3{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(h){this.view=h;for(let H of h.nodes){let q=this.file(H,H.package,void 0);this.topOf.set(H.id,H);for(let $ of H.memberGroups)for(let Z of $.members)this.fileMember(Z,H.package,q.id);if(H.type===rh)this.objects.push(q);else if(H.type===H3)this.templates.push(q);else if(H.type!==bh)this.others.push(q)}for(let H of this.kids.values())H.sort((q,$)=>q.order-$.order||GH(q.id,$.id));this.packages=h.packages.map((H)=>H.name);for(let H of h.requirements){let q=this.byId.get(H.id);if(q===void 0)continue;let $=H.parent!==null?this.reqById.get(H.parent.id):void 0,Z={node:q,req:H,...$!==void 0?{parent:$}:{},children:[],...H.level!==null?{level:H.level}:{},status:H.status,kind:H.subType};if(this.requirements.push(Z),this.reqById.set(H.id,Z),$!==void 0)$.children.push(Z);else this.topRequirements.push(Z)}}file(h,H,q){let $={};for(let K of h.attrs)$[K.name]=K.value;let Z="declaredOn"in h?h.declaredOn:null,z={id:h.id,type:h.type,subType:h.subType,name:h.name,package:H,order:h.order,...q!==void 0?{parent:q}:{},path:h.path,anchor:"anchor"in h?h.anchor:"",...h.extends!==null&&!h.extends.unresolved?{extends:h.extends.id}:{},abstract:h.abstract,isArray:"isArray"in h?h.isArray:!1,...Z!==null&&!Z.unresolved?{inheritedFrom:Z.id}:{},attrs:$,view:h};if(this.byId.set(z.id,z),q!==void 0)this.kids.set(q,[...this.kids.get(q)??[],z]);return z}fileMember(h,H,q){this.file(h,H,q);for(let $ of h.memberGroups)for(let Z of $.members)this.fileMember(Z,H,h.id)}children(h){return this.kids.get(h)??[]}ownerOf(h){let H=this.byId.get(h);while(H?.parent!==void 0)H=this.byId.get(H.parent);return H?.id??h}top(h){return this.topOf.get(h)}fields(h){return this.children(h).filter((H)=>H.type===oh)}source(h){return this.children(h).find((H)=>H.type===k2)}storage(h){let H=this.source(h);if(H===void 0)return;let q=H.attrs[XH],$=H.attrs[KH],Z=H.attrs[WH]===JH||typeof q==="string",z=typeof q==="string"?q:typeof $==="string"?$:void 0;return{kind:Z?"view":"table",...z!==void 0?{name:z}:{}}}isEntity(h){return h.type===rh&&h.subType===S3}isPrompt(h){return h.type===H3&&h.subType===a3}kindOf(h){if(h.type===H3)return h.subType===a3?"prompt":"template";if(h.type!==rh)return"other";if(h.subType===S3)return"entity";if(h.subType===O2)return"value";if(h.subType===P2)return"projection";if(h.subType===A2)return"report";return"object"}storedEntities(){return this.objects.filter((h)=>this.isEntity(h)&&!h.abstract)}claims(h){let H=this.byId.get(h)?.view;if(H===void 0)return[];return H.claims.flatMap((q)=>{let $=this.reqById.get(q.requirement.id);return $===void 0?[]:[{req:$,...q.member!==""?{member:q.member}:{}}]})}generated(h){return(this.topOf.get(h)?.files??[]).flatMap((H)=>H.paths.map((q)=>({path:q,generatedBy:H.generatedBy})))}routes(h){return this.topOf.get(h)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(h){let H=[],q=($)=>{H.push($);for(let Z of $.children)q(Z)};return q(h),H}below(h){return this.subtree(h).slice(1)}rollup(h){let H={};for(let q of h.req.rollup)if(q.count>0)H[q.status]=q.count;return H}targetsOf(h){return h.req.targets.map((H)=>H.id)}linkTargets(h){return h.req.implementedBy.filter((H)=>H.resolves&&this.byId.has(H.target.id)).map((H)=>H.target.id)}featureOf(h){let H=new Map;for(let $ of this.claims(h)){let Z=$.req;while(Z.parent!==void 0)Z=Z.parent;if(Z.kind!==i)continue;H.set(Z,(H.get(Z)??0)+1)}let q;for(let $ of this.features()){let Z=H.get($)??0;if(Z>0&&(q===void 0||Z>(H.get(q)??0)))q=$}return q}features(){return this.topRequirements.filter((h)=>h.kind===i)}qualities(){return this.topRequirements.filter((h)=>h.kind===Jh)}claimStatus(h){let H=this.claims(h);if(H.length===0)return"unclaimed";for(let q of jh)if(H.some(($)=>$.req.status===q))return q;return"unclaimed"}modelEdges(){let h=[],H=new Set;for(let q of this.view.nodes){if(q.type===bh)continue;for(let $ of q.refs){let Z=this.ownerOf($.target.id),z=this.byId.get(Z);if(Z===q.id||z===void 0||z.type===bh)continue;let K=`${$.attr}\x00${q.id}\x00${Z}`;if(H.has(K))continue;H.add(K),h.push({kind:$.attr,from:q.id,to:Z,...$.via!==null?{via:$.via.id}:{}})}}return h.sort((q,$)=>GH(`${q.kind}\x00${q.from}\x00${q.to}`,`${$.kind}\x00${$.from}\x00${$.to}`))}slice(h){return this.view.slices.find((H)=>H.id===h)}}function X(h){return String(h??"").replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H])}function a(h){if(h==="")return"";return`${t3[h]??""} ${X(h)}`}function W3(h){if(h==="")return"";return`${t3[h]??""}`}function r(h){return h.level!==void 0?`L${h.level}`:'—'}var Bh="gate";function J3(h){let H=h.req.diagnostics.filter((z)=>z.source===Bh);if(H.length===0)return"";let q=H.some((z)=>z.severity==="error")?"error":"warn",$=H.map((z)=>z.code).join(", "),Z=H.length;return`${q==="error"?"✕":"!"} ${Z} gate ${q==="error"?Z===1?"error":"errors":Z===1?"warning":"warnings"}`}function _3(h){let H=h.node.attrs[Z3];return typeof H==="string"?`${X(H)}`:""}function ih(h){let H=jh.reduce((Z,z)=>Z+(h[z]??0),0),q=jh.filter((Z)=>(h[Z]??0)>0).map((Z)=>`${h[Z]} ${Z}`).join(", ");if(H===0)return'
    ';let $=jh.filter((Z)=>(h[Z]??0)>0).map((Z)=>``).join("");return``}function Dq(h){return`${(Math.round(h*1e4)/100).toString()}%`}function CH(h){return`
    ${jh.map(($)=>a($)).join("")}${h?'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 U(h,H){let q=h.split("/").length-1;return"../".repeat(q)+H}var j3="index.html",Vh="map.html",dh="requirements/features.html",ch="requirements/qualities.html",w3="matrix.html",ph="trace.html",Dh="prompts.html",Fh="api.html",sh="gaps.html",vh="model/index.html",Fq=new Set([oh,eh,F3,h3,fh,Oh,Ph]),Yq=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),Mq="WARN_REQUIREMENT_OBJECT_UNCLAIMED",wh=(h,H)=>hH?1:0,x=(h)=>typeof h==="string"?h:void 0,o=(h)=>Array.isArray(h)?h.filter((H)=>typeof H==="string"):typeof h==="string"?[h]:[];function kq(h){return h===""?"-root":h.split("::").join("/")}function Kh(h){let H=h.lastIndexOf("::");return H<0?h:h.slice(H+2)}class E3{ix;constructor(h){this.ix=h}objectPage(h){return h.path}packagePage(h){return`model/${kq(h)}/index.html`}reqPage(h){return h.req.path}reqPath(h){return h.req.address}reqLabel(h){return h.req.label}pageOf(h){let H=this.ix.byId.get(h)?.path;return H===void 0||H===""?void 0:H}implLinks(h){return h.req.implementedBy.map((H)=>({ref:H.ref,resolves:H.resolves,...H.resolves&&this.ix.byId.has(H.target.id)?{target:H.target.id}:{}}))}attrValues(h,H){return h.view.attrs.find((q)=>q.name===H)?.values??[]}refLinks(h,H){return this.attrValues(h,H).flatMap((q)=>q.link!==null&&!q.link.unresolved?[q.link]:[])}refHtml(h,H,q,$){return this.attrValues(H,q).filter((Z)=>Z.link!==null).map((Z)=>this.viewLink(h,Z.link,$?.(Z.text))).join(", ")}viewLink(h,H,q){return H.unresolved?`${X(q??Kh(H.label))} (unresolved)`:this.link(h,H.id,q)}memberAnchors(h,H){return this.ix.children(h.id).filter((q)=>!H.has(q.type)&&q.anchor!=="").map((q)=>``).join("")}kindClass(h){return`k-${this.ix.kindOf(h)}`}link(h,H,q){let $=this.pageOf(H),Z=this.ix.byId.get(this.ix.ownerOf(H));if($===void 0||Z===void 0)return`${X(q??Kh(H))} (unresolved)`;let z=this.ix.reqById.get(H),K=q??(z!==void 0?this.reqLabel(z):H===Z.id?Z.name:`${Z.name}.${H.slice(Z.id.length+1)}`);return`${X(K)}`}reqLink(h,H){return`${X(this.reqLabel(H))}`}description(h){return X(x(h.attrs[Wh])??x(h.attrs[l2])??"")}topOf(h){let H=h;while(H.parent!==void 0)H=H.parent;return H}overview(h){let H=this.ix,q=j3,$=H.storedEntities(),Z=H.objects.filter((w)=>H.isEntity(w)&&w.abstract===!0).length,z=H.templates.filter((w)=>H.isPrompt(w)),K=H.objects.filter((w)=>H.kindOf(w)==="value").length,b=H.objects.filter((w)=>H.kindOf(w)==="projection").length,J=H.objects.filter((w)=>H.kindOf(w)==="report").length,V=H.view.counts,W=[];if(W.push({n:`${$.length}`,l:`stored entities${Z>0?` (${Z} abstract base${Z===1?"":"s"})`:""}`,href:U(q,Vh)}),W.push({n:`${z.length}`,l:`declared prompt${z.length===1?"":"s"}, ${T3(K,"payload or reply type","payload and reply types")}`,href:U(q,Dh)}),H.hasRequirements())W.push({n:`${V.requirements}`,l:`requirements: ${T3(V.functional,"feature")}, ${T3(V.architectural,"quality","qualities")}`,href:U(q,dh)});else W.push({n:`${b+J}`,l:`read models: ${b} projection${b===1?"":"s"}, ${J} report${J===1?"":"s"}`,href:U(q,vh)});if(V.coverageMeasured&&V.entitiesTotal>0)W.push({n:`${V.entitiesClaimed}/${V.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:U(q,sh)});else W.push({n:`${H.packages.length}`,l:`package${H.packages.length===1?"":"s"} in the model`,href:U(q,vh)});if(H.view.sources.routes){let w=H.objects.filter((v)=>H.routes(v.id).length>0).length;W.push({n:`${w}`,l:"objects with mounted REST routes",href:U(q,Fh)})}else W.push({n:"—",l:"REST routes: none recorded by this run",href:U(q,Fh)});W.push({n:H.view.sources.files?`${V.files}`:"—",l:H.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:U(q,ph)});let y=["the effective model"];if(H.view.sources.requirements)y.push("the requirement gate's ledger");if(H.view.sources.files)y.push("the generation manifest");return{heading:X(`What ${h} does`),sourcesLine:X(lq(y)),tiles:W.map((w)=>({n:X(w.n),l:X(w.l),href:X(w.href)})),hasRequirements:H.hasRequirements(),featureCards:H.features().map((w)=>this.capCard(q,w)),qualityCards:H.qualities().map((w)=>this.capCard(q,w)),hasFeatures:H.features().length>0,hasQualities:H.qualities().length>0,packageCards:H.packages.map((w)=>this.packageCard(q,w))}}capCard(h,H){let q=this.ix.below(H).length,$=this.ix.targetsOf(H).length;return{levelHtml:r(H),linkHtml:this.reqLink(h,H),statusHtml:a(H.status),verdictHtml:J3(H),statement:X(x(H.node.attrs[uh])??""),barHtml:ih(this.ix.rollup(H)),countsLine:X(`${q} requirement${q===1?"":"s"} below · ${$} model node${$===1?"":"s"} claimed`),children:H.children.map((Z)=>({levelHtml:r(Z),linkHtml:this.reqLink(h,Z),glyphHtml:W3(Z.status)})),hasChildren:H.children.length>0}}packageCard(h,H){let q=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((b)=>b.package===H),$=new Map;for(let b of q)$.set(this.ix.kindOf(b),($.get(this.ix.kindOf(b))??0)+1);let z=["entity","value","projection","report","prompt","template","object","other"].filter((b)=>$.has(b)).map((b)=>`● ${$.get(b)} ${gq(b,$.get(b)??0)}`).join(" · "),K=q.slice(0,12);return{name:X(H===""?"(no package)":H),href:X(U(h,this.packagePage(H))),kindLineHtml:z,membersHtml:K.map((b)=>this.link(h,b.id)).join(", ")+(q.length>K.length?` +${q.length-K.length}`:"")}}map(){let h=this.ix,H=[],q=[{value:"",label:"Whole model"}];if(h.templates.some(($)=>h.isPrompt($)))q.push({value:"@prompts",label:"Prompts and their payloads"});H.push({label:"Model",options:q});for(let $ of h.topRequirements){let Z=[];for(let z of[$,...$.children]){let K=h.slice(`requirement:${z.node.id}`);if(K===void 0)continue;let b=z===$?"":" ";Z.push({value:K.id,label:`${b}${z.level!==void 0?`L${z.level} `:""}${this.reqLabel(z)} (${h.targetsOf(z).length})`})}if(Z.length>0)H.push({label:`${$.kind===i?"Feature":"Quality"}: ${this.reqLabel($)}`,options:Z})}if(h.packages.length>1)H.push({label:"Package",options:h.packages.map(($)=>({value:`package:${$}`,label:$===""?"(no package)":$}))});return{sliceGroups:H.map(($)=>({label:X($.label),options:$.options.map((Z)=>({value:X(Z.value),label:X(Z.label)}))})),hasRequirements:h.hasRequirements()}}object(h){let H=this.ix,q=this.objectPage(h),$=H.kindOf(h),Z=H.claims(h.id),z=H.storage(h.id),K=z===void 0?$==="value"?"value object: no storage":"no source":`${z.kind}${z.name!==void 0?` ${z.name}`:""}`,b=H.fields(h.id).map((d)=>this.fieldRow(q,h,d)),J=b.some((d)=>d.column!==""),V=H.children(h.id).filter((d)=>d.type===eh||d.type===F3||d.type===h3).map((d)=>this.keyRow(q,d)),W=H.children(h.id).filter((d)=>d.type===fh||d.type===Oh||d.type===Ph).map((d)=>this.reportingRow(q,d)),y=H.children(h.id).filter((d)=>d.type===M2).map((d)=>this.layoutRow(d)),w=this.unclaimedEntity(h),v=this.whyRows(q,h),l=H.top(h.id)?.referencedBy??[],k=(d)=>d===Rh||d===X3,D=[...new Set(l.filter((d)=>k(d.attr)).map((d)=>d.from.id))].sort(wh).map((d)=>this.link(q,d)),g=[...new Set(l.filter((d)=>!k(d.attr)).map((d)=>d.from.id))].sort(wh).map((d)=>this.link(q,d)),F=h.extends!==void 0?this.link(q,h.extends):"";return{id:X(h.id),name:X(h.name),kindLabel:X(`object.${h.subType}`),crumbsHtml:`Model › ${X(h.package===""?"(no package)":h.package)} › object.${X(h.subType)}${this.memberAnchors(h,Fq)}`,isAbstract:h.abstract===!0,isUnclaimed:w,isReadOnly:z?.kind==="view",kindBadge:X($),description:this.description(h),storageLine:X(K),extendsHtml:F,whyRows:v,hasWhy:v.length>0,whyEmptyHtml:this.whyEmpty(h),fields:b,hasFields:b.length>0,hasColumn:J,showClaims:this.ix.hasRequirements(),keys:V,hasKeys:V.length>0,reporting:W,hasReporting:W.length>0,layouts:y,hasLayouts:y.length>0,projection:$==="projection"?this.projectionBlock(q,h):void 0,report:$==="report"?this.reportBlock(q,h):void 0,routes:H.routes(h.id).map((d)=>({method:X(d.method),path:X(d.path)})),hasRoutes:H.routes(h.id).length>0,routesNote:!H.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:D.join(", "),referencedByHtml:g.join(", "),generated:this.generatedGroups(h.id),hasGenerated:H.generated(h.id).length>0,generatedNote:!H.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:Z.length}}unclaimedEntity(h){let H=this.ix;if(!H.isEntity(h)||h.abstract===!0)return!1;return H.top(h.id)?.unclaimed===!0}whyRows(h,H){let q=[...this.ix.claims(H.id)].sort((z,K)=>this.ix.requirements.indexOf(z.req)-this.ix.requirements.indexOf(K.req)),$=[],Z;for(let z of q){let K=this.topOf(z.req);$.push({capabilityHtml:K===Z?"":this.reqLink(h,K),reqHtml:this.reqLink(h,z.req),statement:X(x(z.req.node.attrs[uh])??""),levelHtml:r(z.req),statusHtml:a(z.req.status),onHtml:z.member!==void 0?`${X(z.member)}`:'whole object'}),Z=K}return $}whyEmpty(h){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${X(h.name)} exists.`;if(this.unclaimedEntity(h))return`No requirement claims ${X(h.name)}. The gate reports this as ${Mq}.`;return`No requirement claims ${X(h.name)}.`}fieldRow(h,H,q){let $=this.refHtml(h,q,q3),Z=q.subType===Ah?o(q.attrs[l3]):[],z=[];if(q.attrs[Y3]===!0)z.push("required");if(q.attrs[N2]===!0)z.push("filterable");if(q.attrs[f2]===!0)z.push("sortable");if(q.attrs[k3]!==void 0)z.push(`max ${String(q.attrs[k3])}`);if(q.attrs[M3]!==void 0)z.push(`default ${Xh(q.attrs[M3])}`);if(this.ix.children(q.id).some((b)=>b.type===D3))z.push("derived");let K=this.ix.claims(H.id).filter((b)=>b.member!==void 0&&b.member.split(".")[0]===q.name);return{anchor:X(q.anchor),name:X(q.name),inheritedHtml:q.inheritedFrom!==void 0?`inherited`:"",type:X(`${q.subType}${q.isArray===!0?"[]":""}`),refHtml:$!==""?` → ${$}`:"",valuesHtml:Z.length>0?`
    ${Z.map(X).join(" | ")}
    `:"",column:X(x(q.attrs[bH])??""),flagsHtml:z.map((b)=>`${X(b)}`).join(""),claimsHtml:K.map((b)=>`${W3(b.req.status)} ${X(this.reqLabel(b.req))}`).join("
    ")}}keyRow(h,H){let q=o(H.attrs[g3]),$=this.refHtml(h,H,U3)||this.refHtml(h,H,s2),Z=x(H.attrs[a2]),z=x(H.attrs[p2]),K=H.type===h3?[z,Z!==void 0?`through ${Kh(Z)}`:void 0].filter((b)=>b!==void 0).join(", "):`(${q.join(", ")})`;return{anchor:X(H.anchor),kind:X(`${H.type}.${H.subType}`),name:X(H.name),inheritedHtml:H.inheritedFrom!==void 0?'inherited':"",shape:X(K),targetHtml:$!==""?`→ ${$}`:""}}reportingRow(h,H){let q=H.attrs,$=[],Z=x(q[qH]),z=this.refHtml(h,H,e2,Kh);if(Z!==void 0)$.push(`${X(Z)}(${z})`);else if(z!=="")$.push(`of ${z}`);let K=x(q[ZH]),b=x(q[zH]);if(K!==void 0&&b!==void 0)$.push(`${X(K)} ÷ ${X(b)}`);let J=x(q[hH]);if(J!==void 0)$.push(`via ${X(Kh(J))}`);let V=o(q[HH]);if(V.length>0)$.push(`grains ${V.map((y)=>`${X(y)}`).join(" ")}`);let W=x(q[$H]);if(W!==void 0)$.push(`segment ${X(W)}`);if(q[i3]!==void 0)$.push(`filter ${X(Xh(q[i3]))}`);if(q[c3]!==void 0)$.push(`default ${X(Xh(q[c3]))}`);return{anchor:X(H.anchor),kind:X(`${H.type}.${H.subType}`),name:X(H.name),definitionHtml:$.join(" · ")}}layoutRow(h){let H=[],q=o(h.attrs[jH]);if(q.length>0)H.push(`columns ${q.map((Z)=>`${X(Z)}`).join(", ")}`);let $=x(h.attrs[QH]);if($!==void 0)H.push(`sorted by ${X($)}${x(h.attrs[s3])!==void 0?` ${X(x(h.attrs[s3]))}`:""}`);if(typeof h.attrs[p3]==="number")H.push(`${h.attrs[p3]} per page`);return{kind:X(`${h.type}.${h.subType}`),name:X(h.name),detailHtml:H.join(", ")}}projectionBlock(h,H){let q=this.ix,$=[],Z=new Set;for(let z of q.fields(H.id)){if(z.extends!==void 0)Z.add(q.ownerOf(z.extends));for(let K of q.children(z.id).filter((b)=>b.type===D3)){let b=this.originDefinition(h,K);for(let J of this.refLinks(K,z3))Z.add(q.ownerOf(J.id));$.push({field:X(z.name),origin:X(`origin.${K.subType}`),definitionHtml:b})}}return{basesHtml:[...Z].filter((z)=>z!==H.id).sort(wh).map((z)=>this.link(h,z)).join(", "),origins:$,hasOrigins:$.length>0}}originDefinition(h,H){let q=H.attrs,$=(K)=>this.attrValues(H,K).map((b)=>b.link!==null&&!b.link.unresolved?this.link(h,b.link.id,Kh(b.text)):`${X(Kh(b.text))}`).join(", "),Z=[],z=x(q[E2]);if(z!==void 0)Z.push(`${X(z)}(${$(b3)})`);else if(q[b3]!==void 0)Z.push(`of ${$(b3)}`);if(q[z3]!==void 0)Z.push(`from ${$(z3)}`);if(q[A3]!==void 0)Z.push(`via ${X(Kh(String(q[A3])))}`);if(q[R3]!==void 0)Z.push(`${X(Xh(q[R3]))}`);if(q[I3]!==void 0)Z.push(`filter ${X(Xh(q[I3]))}`);return Z.join(" · ")}reportBlock(h,H){let q=H.attrs,$=this.refLinks(H,$3)[0]?.id??x(q[$3]),Z=(K,b)=>{let V=[$!==void 0?`${$}.${K}`:void 0,`${H.package===""?"":`${H.package}::`}${K}`].filter((W)=>W!==void 0).find((W)=>this.ix.byId.get(W)?.type===b||this.ix.byId.has(W)&&K.includes("."));return V!==void 0?this.link(h,V,K):`${X(K)}`},z=x(q[c2]);return{fromHtml:this.refHtml(h,H,$3),spineHtml:z!==void 0?`${X(z)}`:"",dimensionsHtml:o(q[I2]).map((K)=>Z(K,fh)).join(", "),measuresHtml:o(q[R2]).map((K)=>Z(K,Oh)).join(", "),segmentHtml:o(q[i2]).map((K)=>Z(K,Ph)).join(", "),filterHtml:q[x3]!==void 0?`${X(Xh(q[x3]))}`:""}}generatedGroups(h){let H=new Map;for(let q of this.ix.generated(h))H.set(q.generatedBy,[...H.get(q.generatedBy)??[],q.path]);return[...H.keys()].sort(wh).map((q)=>({generator:X(q),files:(H.get(q)??[]).map(($)=>X($))}))}node(h){let H=this.ix,q=this.objectPage(h),$=`${h.type}.${h.subType}`,Z=this.whyRows(q,h),z=this.attrRows(q,h),K=[...(H.top(h.id)?.referencedBy??[]).map((J)=>J.from.id),...H.claims(h.id).map((J)=>this.topOf(J.req).node.id)],b=[...new Set(K.filter((J)=>J!==h.id))].sort(wh).map((J)=>this.link(q,J));return{id:X(h.id),name:X(h.name),kindLabel:X($),crumbsHtml:`Model › ${X(h.package===""?"(no package)":h.package)} › ${X($)}`,isAbstract:h.abstract===!0,description:this.description(h),extendsHtml:h.extends!==void 0?this.link(q,h.extends):"",attrs:z,hasAttrs:z.length>0,members:H.children(h.id).map((J)=>({anchor:X(J.anchor),kind:X(`${J.type}.${J.subType}`),nameHtml:H.reqById.has(J.id)?this.link(q,J.id):X(J.name===""?`#${J.order}`:J.name),attrsHtml:this.attrRows(q,J).map((V)=>`@${V.name} ${V.valueHtml}`).join("
    "),below:H.children(J.id).length})),hasMembers:H.children(h.id).length>0,whyRows:Z,hasWhy:Z.length>0,whyEmptyHtml:this.whyEmpty(h),referencedByHtml:b.join(", "),generated:this.generatedGroups(h.id),hasGenerated:H.generated(h.id).length>0,generatedNote:!H.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(h,H){return H.view.attrs.map((q)=>{let $=q.values.filter((Z)=>Z.link!==null&&!Z.link.unresolved);return{name:X(q.name),valueHtml:$.length>0&&$.length===q.values.length?$.map((Z)=>this.link(h,Z.link.id)).join(", "):`${X(Xh(q.value))}`}})}prompt(h,H){let q=this.ix,$=this.objectPage(h),Z=this.refLinks(h,Rh)[0]?.id,z=this.refLinks(h,X3)[0]?.id,K=H!==void 0?uH(H):void 0,b=Z!==void 0?q.byId.get(Z):void 0,J=z!==void 0?q.byId.get(z):void 0,V=b!==void 0?q.fields(b.id).map((D)=>({name:X(D.name),requiredHtml:D.attrs[Y3]===!0?'required':"",type:X(`${D.subType}${D.isArray===!0?"[]":""}`),refHtml:this.refHtml($,D,q3)!==""?` → ${this.refHtml($,D,q3)}`:"",usedHtml:K===void 0?'text not read':K.has(D.name)?"yes":'no'})):[],W=J!==void 0?q.fields(J.id).map((D)=>({name:X(D.name),type:X(`${D.subType}${D.isArray===!0?"[]":""}`),valuesHtml:D.subType===Ah?`
    ${o(D.attrs[l3]).map(X).join(" | ")}
    `:""})):[],y=x(h.attrs[wH])??"",w=H!==void 0?H.replace(/\n$/,"").split(` -`).length:0,v=[K3,yH,mH,dH,VH].filter((D)=>h.attrs[D]!==void 0).map((D)=>`@${X(D)} ${X(Xh(h.attrs[D]))}`).join(""),l=q.claims(h.id),k=this.whyRows($,h);return{name:X(h.name),kindLabel:X(`template.${h.subType}`),crumbsHtml:`Prompts › ${X(h.package===""?"(no package)":h.package)} › template.${X(h.subType)}${this.memberAnchors(h,new Set)}`,isUnclaimed:q.hasClaims()&&l.length===0,description:this.description(h),attrsHtml:v,payloadHtml:b!==void 0?this.link($,b.id):"none",payloadRows:V,hasPayload:b!==void 0,replyHtml:J!==void 0?this.link($,J.id):"none",replyRows:W,hasReply:J!==void 0,textRef:X(y),textMeta:X(H!==void 0?`${y}.mustache · ${w} line${w===1?"":"s"}${x(h.attrs[K3])!==void 0?` · ${x(h.attrs[K3])}`:""}`:`${y}.mustache`),textHtml:H!==void 0?Sq(H):"",hasText:H!==void 0,generated:this.generatedGroups(h.id),hasGenerated:q.generated(h.id).length>0,generatedNote:!q.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows:k,hasWhy:k.length>0,whyEmptyHtml:q.hasRequirements()?`No requirement claims ${X(h.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 h=Dh,H=this.ix.templates.map((q)=>{let $=this.refHtml(h,q,Rh),Z=this.refHtml(h,q,X3),z=this.ix.claims(q.id);return{linkHtml:this.link(h,q.id),kind:X(`template.${q.subType}`),description:this.description(q),payloadHtml:$!==""?$:'none',replyHtml:Z!==""?Z:'none (outbound only)',claimsHtml:z.length>0?z.map((K)=>a(K.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows:H,hasRows:H.length>0}}requirements(h,H){let q=this.ix.topRequirements.filter((Z)=>Z.kind===h),$=q.length>0?`
      ${q.map((Z)=>this.treeNode(H,Z)).join("")}
    `:"";return{isFeatures:h===i,featuresHref:X(U(H,dh)),qualitiesHref:X(U(H,ch)),featureCount:this.ix.requirements.filter((Z)=>Z.kind===i).length,qualityCount:this.ix.requirements.filter((Z)=>Z.kind===Jh).length,treeHtml:$,hasTree:q.length>0,emptyNote:h===i?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(h,H){let q=this.implLinks(H).map((z)=>{if(z.target!==void 0)return`${this.link(h,z.target,z.ref)}`;return H.status===Qh?`${X(z.ref)} (not yet)`:`${X(z.ref)} (dangling)`}),$=H.children.length>0?`${ih(this.ix.rollup(H))}`:"";return`
  • ${`
    ${r(H)}${this.reqLink(h,H)} ${a(H.status)}${_3(H)}${J3(H)}${$}${q.join("")}
    ${X(x(H.node.attrs[uh])??"")}
    `}${H.children.length>0?`
      ${H.children.map((z)=>this.treeNode(h,z)).join("")}
    `:""}
  • `}requirement(h){let H=this.ix,q=this.reqPage(h),$=[];for(let d=h;d!==void 0;d=d.parent)$.unshift(d);let Z=h.kind===i?{href:dh,label:"Features"}:{href:ch,label:"Qualities"},z=h.req.inLedger,K=h.req.diagnostics,b=this.implLinks(h),J=b.map((d)=>{let B=d.target!==void 0?H.byId.get(d.target):void 0;return{refHtml:B!==void 0?this.link(q,B.id,d.ref):`${X(d.ref)}`,kind:X(B!==void 0?`${B.type}.${B.subType}`:""),resolvesHtml:d.resolves?'resolves':h.status===Qh?'not yet (allowed on planned)':'dangling'}}),V=K.filter((d)=>d.source===Bh),W=K.filter((d)=>d.source!==Bh),y=K.some((d)=>Yq.has(d.code)),w=h.kind===i&&(h.level??0)>=P3,v=b.length===0?"none":b.every((d)=>d.resolves)?"yes":"no",l=H.below(h),k=H.slice(`requirement:${h.node.id}`),D=h;while(D!==void 0&&(D.level??0)>O3)D=D.parent;let g=o(h.node.attrs[t2]),F=this.description(h.node);return{crumbsHtml:`${Z.label} › ${$.map((d)=>d===h?X(this.reqLabel(d)):this.reqLink(q,d)).join(" › ")}`,levelHtml:r(h),name:X(this.reqLabel(h)),statusHtml:a(h.status),dispositionHtml:_3(h),verdictHtml:J3(h),address:X(`${h.req.qualifiedPath} · requirement.${h.kind}`),statement:X(x(h.node.attrs[uh])??""),counterexample:X(x(h.node.attrs[n2])??""),description:F,hasDescription:F!=="",linkRows:J,hasLinks:J.length>0,linksEmpty:h.level!==void 0&&h.levelh.children.length,hasBelow:h.children.length>0,belowBarHtml:ih(H.rollup(h)),children:h.children.map((d)=>({levelHtml:r(d),linkHtml:this.reqLink(q,d),statusHtml:a(d.status)})),sliceHref:k!==void 0?X(`${U(q,Vh)}?slice=${encodeURIComponent(k.id)}`):"",traceHref:D!==void 0?X(`${U(q,ph)}?start=${encodeURIComponent(D.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:v==="none"?'no links':v==="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:y?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:V.length>0?`${V.length}`:z?'none':'not read',how:V.length>0?V.map((d)=>`${X(d.code)} ${X(d.message)}`).join("
    "):z?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:z?`${W.length}`:'not read',how:W.length>0?W.map((d)=>`${X(d.code)} ${X(d.message)}`).join("
    "):z?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:w?'by generator':'not by default',how:w?"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((d)=>({what:X(d.what),verdictHtml:d.verdictHtml,howHtml:d.how})),trackedHtml:g.map((d)=>`${X(d)}`).join(" "),digest:X(h.req.digest)}}matrix(){let h=this.ix,H=w3,q=h.requirements.flatMap((b)=>this.implLinks(b).flatMap((J)=>J.target!==void 0?[h.ownerOf(J.target)]:[])),$=new Set([...h.storedEntities(),...h.templates.filter((b)=>h.isPrompt(b))].map((b)=>b.id));for(let b of q)if(h.byId.get(b)?.parent===void 0&&h.byId.get(b)?.type!==bh)$.add(b);let Z=[...$].map((b)=>h.byId.get(b)).sort((b,J)=>h.claims(J.id).length-h.claims(b.id).length||wh(b.name,J.name)||wh(b.id,J.id)),z=`${Z.map((b)=>`
    ${this.link(H,b.id)}
    `).join("")}`,K=[];for(let b of h.topRequirements){let J=h.subtree(b).filter((V)=>V.req.implementedBy.length>0);if(J.length===0)continue;K.push(`${b.kind===i?"Feature":"Quality"}: ${this.reqLink(H,b)}${Z.map(()=>'').join("")}`);for(let V of J){let W=new Set(this.implLinks(V).filter((w)=>w.target!==void 0).map((w)=>h.ownerOf(w.target))),y=this.reqPath(V).split(".").slice(1).join(".")||this.reqLabel(V);K.push(`${r(V)}${X(y)}${Z.map((w)=>W.has(w.id)?`${W3(V.status)}`:'').join("")}`)}}return{tableHtml:K.length>0?`${z}${K.join("")}
    `:"",hasRows:K.length>0,hasRequirements:h.hasRequirements()}}trace(){let h=this.ix.requirements.filter((q)=>q.level!==void 0&&q.level<=O3),H=h.length===0?this.ix.topRequirements:[];return{options:[...h,...H].map((q)=>({value:X(q.node.id),label:X(`${" ".repeat(Math.max(0,(q.level??1)-1))}${q.level!==void 0?`L${q.level} `:""}${this.reqLabel(q)}`)})),hasStarts:h.length+H.length>0,hasUsage:!1}}gaps(){let h=this.ix,H=sh,q=[],$=(z,K,b,J,V)=>{q.push({title:X(z),count:X(String(K)),source:X(b),isGate:b==="meta verify",whyHtml:J,bodyHtml:V})};if(h.view.sources.requirements){let z=(w)=>[...h.requirements.flatMap((v)=>v.req.diagnostics.filter((l)=>l.source===Bh===w).map((l)=>({req:v,d:l}))),...h.view.advisories.filter((v)=>v.path===""&&v.source===Bh===w).map((v)=>({d:v}))],K=(w,v)=>w.length===0?'
    None.
    ':`${w.map(({req:l,d:k})=>``).join("")}
    ${X(k.code)}${l!==void 0?this.reqLink(H,l):""}
    ${X(k.message)}
    `,b=z(!0);$("Gate findings",b.length,"meta verify","Printed by every run of the requirement gate.",K(b,(w)=>`chip v-${w==="error"?"error":"warn"}`));let J=z(!1);$("Authoring advisories",J.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",K(J,()=>"chip"));let V=h.storedEntities().filter((w)=>this.unclaimedEntity(w));$("Entities no requirement claims",V.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",V.length>0?V.map((w)=>this.link(H,w.id)).join(", "):'
    None.
    ');let W=(w)=>T2.includes(w.status),y=h.requirements.filter((w)=>W(w)&&w.node.attrs[Z3]===void 0&&!h.below(w).some(W));$("Undecided gaps",h.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.",Q3(y.map((w)=>`${r(w)}${this.reqLink(H,w)} ${a(w.status)}`)))}if(h.hasRequirements()){let z=h.requirements.filter((b)=>b.status===Qh&&h.below(b).some((J)=>J.status===Ih));$("Planned, with live work below",z.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.",Q3(z.map((b)=>`${r(b)}${this.reqLink(H,b)} ${a(b.status)} ${ih(h.rollup(b))}`)));let K=h.templates.filter((b)=>h.isPrompt(b)&&h.claims(b.id).length===0);$("Prompts no requirement claims",K.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",K.length>0?K.map((b)=>this.link(H,b.id)).join(", "):'
    None.
    ')}$("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let Z=h.storedEntities().flatMap((z)=>{let K=new Set(h.children(z.id).filter((b)=>b.type===eh&&b.attrs[U3]!==void 0).flatMap((b)=>o(b.attrs[g3])));return h.fields(z.id).filter((b)=>/[a-z]Id$/.test(b.name)&&!K.has(b.name))});if($("Fields that look like references but are not declared",Z.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.",Q3(Z.map((z)=>`${this.link(H,z.id)} ${X(z.subType)}`))),h.templates.length>0){let z=this.unusedPayload();$("Payload fields the prompt text never uses",z===void 0?"—":z.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.",z===void 0?'
    No prompt text was read.
    ':Q3(z.map(({p:K,f:b})=>`${this.link(H,K.id)}: ${this.link(H,b.id,b.name)}`)))}return{cards:q}}texts=new Map;unusedPayload(){let h=[],H=!1;for(let q of this.ix.templates){let $=this.texts.get(q.id),Z=this.refLinks(q,Rh)[0]?.id;if($===void 0||Z===void 0)continue;H=!0;let z=uH($);for(let K of this.ix.fields(Z))if(!z.has(K.name))h.push({p:q,f:K})}return H?h:void 0}api(){let h=this.ix,H=Fh,q=h.objects.filter((Z)=>h.routes(Z.id).length>0).map((Z)=>({linkHtml:this.link(H,Z.id),kind:X(h.kindOf(Z)),isReadOnly:h.storage(Z.id)?.kind==="view",routes:h.routes(Z.id).map((z)=>({method:X(z.method),methodClass:X(z.method.toLowerCase()),path:X(z.path)}))})),$=q.reduce((Z,z)=>Z+z.routes.length,0);return{groups:q,hasGroups:q.length>0,recorded:h.view.sources.routes,summary:X(`${$} route${$===1?"":"s"} on ${q.length} object${q.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((h)=>this.packageCard(vh,h))}}packageIndex(h){let H=this.ix,q=this.packagePage(h),$=[...H.objects,...H.templates,...H.others].filter((Z)=>Z.package===h).map((Z)=>{let z=H.storage(Z.id),K=H.claimStatus(Z.id);return{linkHtml:this.link(q,Z.id),kind:X(`${Z.type}.${Z.subType}`),abstractHtml:Z.abstract===!0?'abstract':"",storage:X(z===void 0?"":`${z.kind}${z.name!==void 0?` ${z.name}`:""}`),fieldCount:H.fields(Z.id).length,statusHtml:K==="unclaimed"?this.unclaimedEntity(Z)?'unclaimed':"":a(K),description:this.description(Z)}});return{name:X(h===""?"(no package)":h),crumbsHtml:`Model › ${X(h===""?"(no package)":h)}`,rows:$}}}function Q3(h){return h.length===0?'
    None.
    ':`
      ${h.map((H)=>`
    • ${H}
    • `).join("")}
    `}function Xh(h){return typeof h==="string"?h:JSON.stringify(h)}function lq(h){return h.length<=1?h[0]??"":`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`}function T3(h,H,q=`${H}s`){return`${h} ${h===1?H:q}`}function gq(h,H){if(H===1)return h;return h==="entity"?"entities":`${h}s`}var Uq=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function uH(h){let H=new Set;for(let q of h.matchAll(Uq))if(q[1]!=="/")H.add(q[2].split(".")[0]);return H}function Sq(h){let H="",q=0;for(let $ of h.matchAll(/\{\{[^}]*\}?\}\}/g))H+=X(h.slice(q,$.index)),H+=`${X($[0])}`,q=$.index+$[0].length;return H+X(h.slice(q))}var xq=[{key:"overview",label:"Overview",href:j3},{key:"map",label:"Model map",href:Vh},{key:"requirements",label:"Requirements",href:dh},{key:"matrix",label:"Matrix",href:w3},{key:"trace",label:"Trace",href:ph},{key:"prompts",label:"Prompts",href:Dh},{key:"api",label:"API",href:Fh},{key:"gaps",label:"Gaps",href:sh}];function Lq(h){if(h===void 0)return new Map;if(h instanceof Map)return h;return new Map(Object.entries(h))}function BH(h){let H=new n3(h.view),q=new E3(H),$=Lq(h.texts);for(let[y,w]of $)q.texts.set(y,w);let Z=(y)=>{let w=h.templates[y];if(w===void 0)throw Error(`docs-site explorer: no template ${y}`);return w},z=new Eh({card:Z("explorer-card.mustache")}),K=Z("explorer-head.mustache"),b=Z("explorer-foot.mustache"),J=CH(H.hasClaims()),V=new Map,W=(y,w,v,l,k,D=!1)=>{if(V.has(w))throw Error(`docs-site explorer: two pages map to ${w}`);let g=Z(y);V.set(w,()=>{let F=U(w,""),d={...k(),siteTitle:X(h.title),pageTitle:X(l),stamp:X(h.stamp??""),relRoot:F,assetBase:h.assetBase,cytoscapeSrc:h.cytoscapeSrc(F),graph3dSrc:h.graph3dSrc(F),needsGraph:D,pageKey:v,nav:xq.map((B)=>({label:B.label,href:U(w,B.href),on:B.key===v})),legendHtml:J};return v3({template:K+g+b,payload:d,provider:z,format:"text"})})};W("explorer-overview.html.mustache",j3,"overview","Overview",()=>q.overview(h.title)),W("explorer-map.html.mustache",Vh,"map","Model map",()=>q.map(),!0),W("explorer-requirements.html.mustache",dh,"requirements","Features",()=>q.requirements(i,dh)),W("explorer-requirements.html.mustache",ch,"requirements","Qualities",()=>q.requirements(Jh,ch)),W("explorer-matrix.html.mustache",w3,"matrix","Matrix",()=>q.matrix()),W("explorer-trace.html.mustache",ph,"trace","Trace",()=>q.trace(),!0),W("explorer-prompts.html.mustache",Dh,"prompts","Prompts",()=>q.prompts()),W("explorer-api.html.mustache",Fh,"api","API",()=>q.api()),W("explorer-gaps.html.mustache",sh,"gaps","Gaps",()=>q.gaps()),W("explorer-model.html.mustache",vh,"map","Packages",()=>q.model());for(let y of H.packages)W("explorer-package.html.mustache",q.packagePage(y),"map",y===""?"(no package)":y,()=>q.packageIndex(y));for(let y of H.objects)W("explorer-object.html.mustache",q.objectPage(y),"map",y.name,()=>q.object(y),!0);for(let y of H.templates)W("explorer-prompt.html.mustache",q.objectPage(y),"prompts",y.name,()=>q.prompt(y,$.get(y.id)));for(let y of H.others)W("explorer-node.html.mustache",q.objectPage(y),"map",y.name,()=>q.node(y));for(let y of H.requirements)W("explorer-requirement.html.mustache",q.reqPage(y),"requirements",q.reqLabel(y),()=>q.requirement(y));return{pages:V,graphData:()=>Nq(H,q)}}function Nq(h,H){let q=h.features(),$=[...h.objects,...h.templates],Z=$.map((W)=>{let y=h.featureOf(W.id),w=h.claims(W.id);return{id:W.id,name:W.name,kind:h.kindOf(W),pkg:W.package,href:H.objectPage(W),abstract:W.abstract===!0?1:0,fields:h.fields(W.id).length,claims:w.length,status:h.claimStatus(W.id),feature:y!==void 0?q.indexOf(y):-1,quality:w.length>0&&w.every((v)=>v.req.kind===Jh)?1:0,unclaimed:H.unclaimedEntity(W)?1:0,api:h.routes(W.id).map((v)=>`${v.method} ${v.path}`),gen:h.generated(W.id).length,storage:h.storage(W.id)?.kind??""}}),z=new Set($.map((W)=>W.id)),K={};for(let W of h.view.slices)K[W.id]=[...new Set(W.nodes.map((y)=>h.ownerOf(y)).filter((y)=>z.has(y)))].sort();let b=h.requirements.map((W)=>({id:W.node.id,label:H.reqLabel(W),path:H.reqPath(W),level:W.level??0,status:W.status,kind:W.kind,parent:W.parent?.node.id??"",href:H.reqPage(W),targets:h.linkTargets(W).map((y)=>h.ownerOf(y)),statement:W.req.statement,rollup:h.rollup(W),claimed:h.targetsOf(W).length})),J={};for(let W of $){let y=new Map;for(let w of h.generated(W.id))y.set(w.generatedBy,(y.get(w.generatedBy)??0)+1);if(y.size>0)J[W.id]=[...y.entries()].sort((w,v)=>w[0]v[0]?1:0)}let V=[];for(let W of $){let y=typeof W.attrs[Wh]==="string"?W.attrs[Wh]:"";V.push({t:W.name,s:`${W.type}.${W.subType}${W.package!==""?` · ${W.package}`:""}`,h:H.objectPage(W),k:`${W.name} ${W.id} ${y}`.toLowerCase()});for(let w of h.fields(W.id)){if(w.inheritedFrom!==void 0)continue;V.push({t:`${W.name}.${w.name}`,s:`field.${w.subType}`,h:H.pageOf(w.id)??H.objectPage(W),k:`${W.name}.${w.name} ${w.id}`.toLowerCase()})}}for(let W of h.others){let y=typeof W.attrs[Wh]==="string"?W.attrs[Wh]:"";V.push({t:W.name,s:`${W.type}.${W.subType}${W.package!==""?` · ${W.package}`:""}`,h:H.objectPage(W),k:`${W.name} ${W.id} ${y}`.toLowerCase()})}for(let W of h.requirements)V.push({t:H.reqLabel(W),s:`${W.level!==void 0?`L${W.level}`:"—"} ${W.kind}${W.status!==""?` · ${W.status}`:""} · ${H.reqPath(W)}`,h:H.reqPage(W),k:`${H.reqPath(W)} ${W.node.id} ${H.reqLabel(W)} ${W.req.statement}`.toLowerCase()});return{nodes:Z,edges:h.modelEdges().filter((W)=>z.has(W.from)&&z.has(W.to)).map((W)=>({s:W.from,t:W.to,k:W.kind,...W.via!==void 0?{v:fq(W.via)}:{}})),slices:K,features:q.map((W)=>({id:W.node.id,label:H.reqLabel(W)})),reqs:b,generated:J,search:V,hasClaims:h.hasClaims(),requirementType:bh}}function fq(h){let H=h.lastIndexOf(".");return H<0?h:h.slice(H+1)}function vH(h){return BH({view:h.view,title:h.title,templates:{...V3,...h.templates},texts:h.texts,...h.footer!==""&&{stamp:h.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor:vH,templates:V3};if(typeof document<"u")Oq(window);function Oq(h){let $,Z="",z={path:"",search:""},K=[],b=(C)=>{let Y=C.replace(/^#\/?/,""),j=new URL(Y===""?"index.html":Y,"http://explorer.invalid/"),Q=j.pathname.slice(1);try{Q=decodeURIComponent(Q)}catch{}return{path:Q===""?"index.html":Q,search:j.search,anchor:j.hash.slice(1)}},J=(C,Y,j="")=>`#/${C}${Y}${j!==""?`#${j}`:""}`;h.MO_APP={href:(C)=>{let Y=b(C);return J(Y.path,Y.search,Y.anchor)},search:()=>z.search,replaceQuery:(C)=>{z={path:z.path,search:C==="?"?"":C},history.replaceState(null,"",J(z.path,z.search))},listen:(C,Y)=>{document.addEventListener(C,Y),K.push(()=>document.removeEventListener(C,Y))},onLeave:(C)=>{K.push(C)}};let V=(C=h.MO_MODEL)=>{if(C===void 0)return!1;return $=vH(C),h.MO_EXPLORER=$.graphData(),Z=C.stamp,!0},y=new URLSearchParams(location.search).get("source"),w,v;if(y!==null&&y!=="")try{w=new URL(y,location.href)}catch{}let l=()=>{if(y===null||y==="")return;let C=v?.ok??!1,Y=r3(w?.href??y),j=C?`● Following the running application at ${Y}`:`● Cannot read ${Y}${v!==void 0&&v.error!==""?` (${r3(v.error)})`:""}${$!==void 0?", showing the model it last served":""}; trying again every second`,Q=document.getElementById("mo-live");if(Q===null)Q=document.createElement("div"),Q.id="mo-live",document.body.appendChild(Q);if(Q.innerHTML!==j)Q.innerHTML=j;let m=C?"live-source":"live-source down";if(Q.className!==m)Q.className=m;if(v!==void 0)Q.dataset.checked=new Date(v.at).toISOString();document.documentElement.setAttribute("data-mo-source",C?"live":"down")},k=(C,Y,j)=>{for(let Q of Array.from(C.querySelectorAll("a[href]"))){let m=Q.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(m))continue;if(m.startsWith("#")){Q.setAttribute("href",J(Y,j,m.slice(1)));continue}let G=new URL(m,"http://explorer.invalid/"+Y);Q.setAttribute("href",J(G.pathname.slice(1),G.search,G.hash.slice(1)))}},D=(C)=>{let Y=b(location.hash),j=$?.pages.get(Y.path);for(let u of K)u();K=[],z={path:Y.path,search:Y.search};let Q=j!==void 0?j():`Not found

    No such page

    ${r3(Y.path)} is not a page of this model.

    Overview

    `,m=new DOMParser().parseFromString(Q,"text/html");m.querySelectorAll("script").forEach((u)=>u.remove()),k(m,Y.path,Y.search);let G=window.scrollY;document.title=m.title;for(let u of Array.from(document.body.attributes))document.body.removeAttribute(u.name);for(let u of Array.from(m.body.attributes))document.body.setAttribute(u.name,u.value);if(document.body.replaceChildren(...Array.from(m.body.childNodes).map((u)=>document.importNode(u,!0))),j!==void 0)h.MO_THEME?.();if(C)window.scrollTo(0,G);else if(Y.anchor!=="")document.getElementById(Y.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",Y.path),l()};window.addEventListener("hashchange",()=>{let C=b(location.hash);if(C.path===z.path&&C.search===z.search){if(C.anchor!=="")document.getElementById(C.anchor)?.scrollIntoView();return}D(!1)});let g=(C,Y)=>{let j=document.createElement("script");j.src=`${C}?t=${Date.now()}`,j.onload=()=>{j.remove(),Y()},j.onerror=()=>{j.remove(),Y()},document.head.appendChild(j)},F=()=>{g("explorer-stamp.js",()=>{if(h.MO_STAMP===void 0||h.MO_STAMP===Z)return void setTimeout(F,1000);let C=h.MO_STAMP;g("explorer-model.js",()=>{if(h.MO_MODEL?.stamp===C&&V())D(!0);setTimeout(F,1000)})})},d=(C)=>{let Y="",j=async()=>{try{let Q=await fetch(C.href,{cache:"no-cache"});if(!Q.ok)throw Error(`HTTP ${Q.status}`);let m=await Q.text();if(m!==Y){let G=JSON.parse(m);if(typeof G!=="object"||G===null||!String(G.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let u=h.MO_MODEL,M=$===void 0;V({stamp:Q.headers.get("etag")??`${m.length}`,title:u?.title??C.host,footer:u?.footer??"",texts:u?.texts??{},templates:u?.templates??{},view:G}),Y=m,v={ok:!0,at:Date.now(),error:""},D(!M)}else v={ok:!0,at:Date.now(),error:""},l()}catch(Q){if(v={ok:!1,at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},$===void 0)document.body.innerHTML="

    No model yet

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

    ";l()}setTimeout(()=>void j(),1000)};j()},B=()=>{if(y!==null&&y!==""){if(w===void 0){v={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",l();return}d(w);return}if(!V())document.body.innerHTML="

    No model

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

    ";else D(!1);setTimeout(F,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",B);else B()}function r3(h){return h.replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H])}})(); + */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/typescript/packages/docs-site/app/assets/explorer-app.js b/server/typescript/packages/docs-site/app/assets/explorer-app.js index 3a52a6d4e0..dd2a04d098 100644 --- a/server/typescript/packages/docs-site/app/assets/explorer-app.js +++ b/server/typescript/packages/docs-site/app/assets/explorer-app.js @@ -11,7 +11,7 @@ * * 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. */ -(()=>{var V3={"explorer-head.mustache":` +(()=>{var explorer_templates_default={"explorer-head.mustache":` @@ -260,10 +260,10 @@ `};/*! * mustache.js - Logic-less {{mustache}} templates with JavaScript * http://github.com/janl/mustache.js - */var DH=Object.prototype.toString,Gh=Array.isArray||function(H){return DH.call(H)==="[object Array]"};function m3(h){return typeof h==="function"}function FH(h){return Gh(h)?"array":typeof h}function d3(h){return h.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function o3(h,H){return h!=null&&typeof h==="object"&&H in h}function YH(h,H){return h!=null&&typeof h!=="object"&&h.hasOwnProperty&&h.hasOwnProperty(H)}var MH=RegExp.prototype.test;function kH(h,H){return MH.call(h,H)}var lH=/\S/;function gH(h){return!kH(lH,h)}var UH={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function SH(h){return String(h).replace(/[&<>"'`=\/]/g,function(q){return UH[q]})}var xH=/\s*/,LH=/\s+/,e3=/\s*=/,NH=/\s*\}/,fH=/#|\^|\/|>|\{|&|=|!/;function OH(h,H){if(!h)return[];var q=!1,$=[],Z=[],z=[],K=!1,b=!1,J="",V=0;function W(){if(K&&!b)while(z.length)delete Z[z.pop()];else z=[];K=!1,b=!1}var y,w,v;function l(Q){if(typeof Q==="string")Q=Q.split(LH,2);if(!Gh(Q)||Q.length!==2)throw Error("Invalid tags: "+Q);y=new RegExp(d3(Q[0])+"\\s*"),w=new RegExp("\\s*"+d3(Q[1])),v=new RegExp("\\s*"+d3("}"+Q[1]))}l(H||p.tags);var k=new Mh(h),D,g,F,d,B,C;while(!k.eos()){if(D=k.pos,F=k.scanUntil(y),F)for(var Y=0,j=F.length;Y")B=[g,F,D,k.pos,J,V,q];else B=[g,F,D,k.pos];if(V++,Z.push(B),g==="#"||g==="^")$.push(B);else if(g==="/"){if(C=$.pop(),!C)throw Error('Unopened section "'+F+'" at '+D);if(C[1]!==F)throw Error('Unclosed section "'+C[1]+'" at '+D)}else if(g==="name"||g==="{"||g==="&")b=!0;else if(g==="=")l(F)}if(W(),C=$.pop(),C)throw Error('Unclosed section "'+C[1]+'" at '+k.pos);return AH(PH(Z))}function PH(h){var H=[],q,$;for(var Z=0,z=h.length;Z0?$[$.length-1][4]:H;break;default:q.push(Z)}return H}function Mh(h){this.string=h,this.tail=h,this.pos=0}Mh.prototype.eos=function(){return this.tail===""};Mh.prototype.scan=function(H){var q=this.tail.match(H);if(!q||q.index!==0)return"";var $=q[0];return this.tail=this.tail.substring($.length),this.pos+=$.length,$};Mh.prototype.scanUntil=function(H){var q=this.tail.search(H),$;switch(q){case-1:$=this.tail,this.tail="";break;case 0:$="";break;default:$=this.tail.substring(0,q),this.tail=this.tail.substring(q)}return this.pos+=$.length,$};function yh(h,H){this.view=h,this.cache={".":this.view},this.parent=H}yh.prototype.push=function(H){return new yh(H,this)};yh.prototype.lookup=function(H){var q=this.cache,$;if(q.hasOwnProperty(H))$=q[H];else{var Z=this,z,K,b,J=!1;while(Z){if(H.indexOf(".")>0){z=Z.view,K=H.split("."),b=0;while(z!=null&&b")V=this.renderPartial(b,q,$,z);else if(J==="&")V=this.unescapedValue(b,q);else if(J==="name")V=this.escapedValue(b,q,z);else if(J==="text")V=this.rawValue(b);if(V!==void 0)K+=V}return K};O.prototype.renderSection=function(H,q,$,Z,z){var K=this,b="",J=q.lookup(H[1]);function V(w){return K.render(w,q,$,z)}if(!J)return;if(Gh(J))for(var W=0,y=J.length;W0||!$))z[K]=Z+z[K];return z.join(` -`)};O.prototype.renderPartial=function(H,q,$,Z){if(!$)return;var z=this.getConfigTags(Z),K=m3($)?$(H[1]):$[H[1]];if(K!=null){var b=H[6],J=H[5],V=H[4],W=K;if(J==0&&V)W=this.indentPartial(K,V,b);var y=this.parse(W,z);return this.renderTokens(y,q,$,W,Z)}};O.prototype.unescapedValue=function(H,q){var $=q.lookup(H[1]);if($!=null)return $};O.prototype.escapedValue=function(H,q,$){var Z=this.getConfigEscape($)||p.escape,z=q.lookup(H[1]);if(z!=null)return typeof z==="number"&&Z===p.escape?String(z):Z(z)};O.prototype.rawValue=function(H){return H[1]};O.prototype.getConfigTags=function(H){if(Gh(H))return H;else if(H&&typeof H==="object")return H.tags;else return};O.prototype.getConfigEscape=function(H){if(H&&typeof H==="object"&&!Gh(H))return H.escape;else return};var p={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(h){Yh.templateCache=h},get templateCache(){return Yh.templateCache}},Yh=new O;p.clearCache=function(){return Yh.clearCache()};p.parse=function(H,q){return Yh.parse(H,q)};p.render=function(H,q,$,Z){if(typeof H!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+FH(H)+'" was given as the first argument for mustache#render(template, view, partials)');return Yh.render(H,q,$,Z)};p.escape=SH;p.Scanner=Mh;p.Context=yh;p.Writer=O;var Hh=p;var y3=(h)=>h.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),IH=/^-?[0-9]+(\.[0-9]+)?$/,H2=(h)=>/^[=+\-@\t\r]/.test(h)&&!IH.test(h)?"'"+h:h,RH=(h)=>{let H=H2(h);return/[",\n\r]/.test(H)?`"${H.replace(/"/g,'""')}"`:H},iH=(h)=>JSON.stringify(h).slice(1,-1),h2=(h)=>h,q2={text:h2,markdown:h2,html:y3,xml:y3,json:iH,csv:RH,spreadsheet:(h)=>H2(y3(h))};var $2="has";function ah(h){return"has"+cH(h)}var kh="-last";function cH(h){if(h.length===0)return h;let H=h.charAt(0);if(H===H.toUpperCase()&&H!==H.toLowerCase())return h;return H.toUpperCase()+h.slice(1)}function Z2(h){if(h===null||h===void 0)return!1;if(typeof h==="string")return h.trim().length>0;if(Array.isArray(h))return h.length>0;if(typeof h==="number"||typeof h==="boolean"||typeof h==="bigint")return;return typeof h==="object"}function z2(h,H=0){return lh(h,H,void 0)}function lh(h,H,q){if(H>32)return h;if(Array.isArray(h)){let K=h.length-1;return h.map((b,J)=>lh(b,H+1,J===K))}if(h===null||typeof h!=="object")return h;let $=Object.getPrototypeOf(h);if($!==Object.prototype&&$!==null)return sH(h,H,q);let Z=h,z={};for(let[K,b]of Object.entries(Z))z[K]=lh(b,H+1,void 0);for(let[K,b]of Object.entries(Z)){let J=ah(K);if(Object.prototype.hasOwnProperty.call(Z,J))continue;let V=Z2(b);if(V!==void 0)z[J]=V}if(q!==void 0&&!Object.prototype.hasOwnProperty.call(Z,kh))z[kh]=q;return z}function pH(h){return h.length===0?h:h.charAt(0).toLowerCase()+h.slice(1)}function sH(h,H,q){let $=new Map,Z=(K)=>{if($.has(K))return $.get(K);let b=Reflect.get(h,K,h),J=typeof b==="function"?(...V)=>lh(Reflect.apply(b,h,V),H+1,void 0):lh(b,H+1,void 0);return $.set(K,J),J},z=(K)=>{if(typeof K!=="string")return;if(K===kh)return q;if(!K.startsWith("has"))return;let b=K.slice(3);for(let J of[pH(b),b]){if(!(J in h)||ah(J)!==K)continue;let V=Reflect.get(h,J,h);if(typeof V==="function")continue;let W=Z2(V);if(W!==void 0)return W}return};return new Proxy(Object.create(null),{has:(K,b)=>(b in h)||z(b)!==void 0,get:(K,b)=>(b in h)?Z(b):z(b)})}var b2=["mustache","jinja"],gh="mustache",e="jinja";var K2=[".jinja",".j2",".jinja2"];function qh(h,H,q){let $=h.engineOf?.(H);return $!==void 0&&$!==q}function th(h,H){return`ERR_TEMPLATE_ENGINE_UNSUPPORTED: partial ${h} is not a ${H} template; a ${H} body includes only ${H} partials`}function X2(h,H,q){if(q!==void 0){if(!b2.includes(q))throw Error(`unknown template engine ${JSON.stringify(q)}; expected one of ${b2.join(", ")}`);return q}if(h!==void 0&&H!==void 0){let $=h.engineOf?.(H);if($!==void 0)return $}return"mustache"}var R="ERR_VAR_NOT_ON_PAYLOAD",Uh="ERR_PARTIAL_UNRESOLVED",G3="ERR_REQUIRED_SLOT_UNUSED";var Sh="ERR_TEMPLATE_NOT_STATIC",$h="ERR_TEMPLATE_SYNTAX",xh="ERR_TEMPLATE_ENGINE_UNSUPPORTED",t=32,aH=new Set([">"," ","\t",` -`,"\r"]);function tH(h,H){let q=`<${H}`;for(let $=h.indexOf(q);$!==-1;$=h.indexOf(q,$+1)){let Z=h[$+q.length];if(Z!==void 0&&aH.has(Z))return!0}return!1}function nH(h,H){return h.includes(``)}function nh(h,H,q){let $=[];for(let z of q?.requiredSlots??[])if(!h.has(z))$.push({code:"ERR_REQUIRED_SLOT_UNUSED",path:z});let Z=q?.requiredTags??[];if(Z.length>0){let z=H.join(` -`);for(let K of Z)if(!tH(z,K)||!nH(z,K))$.push({code:"ERR_OUTPUT_TAG_MISSING",path:K})}return $}var _H=()=>{throw Error("the explorer app renders Mustache only")},C3=new Proxy({},{get:()=>_H});var Zh=C3;function Lh(h){return Zh.parser.parse(h)}function zh(h){return typeof h==="object"&&h!==null&&typeof h.typename==="string"}function I(h){let H=[],q=($)=>{if(Array.isArray($))$.forEach(q);else if(zh($))H.push($)};for(let $ of h.fields)q(h[$]);if(h.typename==="Set")q(h.body);return H}function Nh(h){for(let H of K2)if(h.toLowerCase().endsWith(H))return h.slice(0,-H.length);return h}function TH(h){return function(H,q){this._emit("runtime.markSafe("),h.call(this,H,q),this._emit(")")}}function EH(h){let H={getSource(q){let $=h.resolve(Nh(q));return $===void 0?null:{src:$,path:q,noCache:!0}}};return new C3.Environment(H,{autoescape:!0,throwOnUndefined:!0,trimBlocks:!1,lstripBlocks:!1})}function rH(h){if(h===void 0)throw Error(`render verify failed: ${R}`);return h}function W2(h,H,q,$){let Z=EH(q),z=Zh.compiler.Compiler.prototype,K=Zh.lib.escape,b=z.compileCapture,J=Zh.runtime.ensureDefined;Zh.runtime.ensureDefined=rH,Zh.lib.escape=(V)=>$(typeof V==="string"?V:String(V)),z.compileCapture=TH(b);try{return Z.renderString(h,H)}finally{Zh.lib.escape=K,z.compileCapture=b,Zh.runtime.ensureDefined=J}}var S={tag:"opaque"},oH=new Set(["range","cycler","joiner","namespace","dict","lipsum","super","self"]),eH=new Set(["first","last","random"]),hq=new Set(["sort","reverse","list","unique","selectattr","rejectattr","default","d"]),Hq=new Map([["selectattr",0],["rejectattr",0],["groupby",0],["sum",0],["join",1],["min",1],["max",1],["unique",1],["sort",2]]),qq="attribute";function J2(h,H){return{tag:"typed",fields:h.fields,isArray:h.isArray===!0,path:H}}function Q2(h,H){if(h.tag==="opaque")return S;return{tag:"typed",fields:h.isArray?h.fields:void 0,isArray:!1,path:H}}function u3(h){if(h.kind==="key")return`.${h.key}`;if(h.kind==="index")return`[${h.index}]`;return"[*]"}function j2(h,H,q){let $=[],Z=q?.provider,z=new Set,K=[h],b=(j,Q)=>{$.push({code:j,path:Q})};function J(j,Q){for(let G=Q.frames.length-1;G>=0;G--){let u=Q.frames[G].get(j);if(u!==void 0)return u}let m=Q.root.find((G)=>G.name===j);if(m!==void 0){if(Q.root===H)z.add(j);return J2(m,j)}return oH.has(j)?S:void 0}function V(j,Q,m){j.frames[j.frames.length-1].set(Q,m)}function W(j){return{...j,frames:[...j.frames,new Map]}}function y(j){let Q=[],m=j;while(m.typename==="LookupVal"){let G=m.val;if(G.typename==="Literal"&&typeof G.value==="string")Q.unshift({kind:"key",key:G.value});else if(G.typename==="Literal"&&typeof G.value==="number")Q.unshift({kind:"index",index:G.value});else Q.unshift({kind:"dynamic",node:G});m=m.target}return{base:m,segments:Q}}function w(j,Q){let{base:m,segments:G}=y(j);for(let L of G)if(L.kind==="dynamic")B(L.node,Q);let u,M;if(m.typename==="Symbol"){M=m.value;let L=M+G.map(u3).join(""),c=J(M,Q);if(c===void 0)return b(R,L),S;u=c}else u=B(m,Q),M=u.tag==="typed"?u.path:"";let s=M+G.map(u3).join("");for(let L of G){if(u.tag==="opaque")return S;if(M+=u3(L),L.kind==="key"){let c=u.isArray?void 0:u.fields?.find((mh)=>mh.name===L.key);if(c===void 0)return b(R,s),S;u=J2(c,M)}else if(u.isArray)u={tag:"typed",fields:u.fields,isArray:!1,path:M};else if(L.kind==="dynamic"&&u.fields!==void 0)return b(Sh,s),S;else u={tag:"typed",fields:u.fields,isArray:!1,path:M}}return u}function v(j,Q,m){if(j.tag==="opaque"){B(Q,m);return}if(Q.typename!=="Literal"||typeof Q.value!=="string"){B(Q,m),b(Sh,`${j.path}[*]`);return}let G=Q.value,u=j.fields;for(let M of G.split(".")){let s=u?.find((L)=>L.name===M);if(s===void 0){b(R,`${j.path}.${G}`);return}u=s.fields}}function l(j){let Q=[],m=[];for(let G of j===void 0?[]:I(j))if(G.typename==="KeywordArgs")for(let u of I(G)){let M=u.key;m.push([String(M.value),u.value])}else Q.push(G);return{positional:Q,keywords:m}}function k(j,Q){let m=String(j.name.value),{positional:G,keywords:u}=l(j.args),[M,...s]=G,L=M===void 0?S:B(M,Q);s.forEach((c,mh)=>{if(mh===Hq.get(m))v(L,c,Q);else B(c,Q)});for(let[c,mh]of u)if(c===qq)v(L,mh,Q);else B(mh,Q);if(eH.has(m))return L.tag==="typed"?Q2(L,`${L.path}|${m}`):S;if(hq.has(m))return L;return S}function D(j,Q){let m=j.name;if(m.typename==="LookupVal")B(m.target,Q);else if(m.typename==="Symbol"){let M=m.value;if(J(M,Q)===void 0)b(R,M)}else B(m,Q);let{positional:G,keywords:u}=l(j.args);return G.forEach((M)=>B(M,Q)),u.forEach(([,M])=>B(M,Q)),S}function g(j,Q){let m=W(Q);for(let G of["caller","varargs","kwargs"])V(m,G,S);for(let G of I(j.args))if(G.typename==="Symbol")V(m,G.value,S);else if(G.typename==="KeywordArgs")for(let u of I(G))B(u.value,Q),V(m,String(u.key.value),S);C(j.body,m)}function F(j,Q,m,G,u=!1){if(Q.typename!=="Literal"||typeof Q.value!=="string"){B(Q,m),b(Sh,j);return}if(Z===void 0)return;let M=Nh(Q.value);if(m.seen.includes(M)||m.seen.length>=t)return;let s=Z.resolve(M);if(s===void 0){if(!u)b(Uh,M);return}if(qh(Z,M,e)){b(xh,M);return}K.push(s);let L;try{L=Lh(s)}catch(c){b($h,`${M}: ${c.message}`);return}C(L,G(m,M))}function d(j,Q,m){if(j.typename==="Symbol")V(m,j.value,Q);else for(let G of I(j))d(G,S,m)}function B(j,Q){switch(j.typename){case"Symbol":case"LookupVal":return w(j,Q);case"Literal":case"TemplateData":return S;case"Group":{let m=I(j);if(m.length===1)return B(m[0],Q);return m.forEach((G)=>B(G,Q)),S}case"Filter":case"FilterAsync":return k(j,Q);case"FunCall":return D(j,Q);case"Caller":return g(j,Q),S;case"Is":{B(j.left,Q);let m=j.right;if(m.typename==="FunCall"){let{positional:G,keywords:u}=l(m.args);G.forEach((M)=>B(M,Q)),u.forEach(([,M])=>B(M,Q))}return S}case"Pair":{let m=j.key;if(m.typename!=="Symbol")B(m,Q);return B(j.value,Q),S}case"Capture":return C(j.body,Q),S;default:for(let m of I(j))B(m,Q);return S}}function C(j,Q){switch(j.typename){case"Root":case"NodeList":for(let m of I(j))C(m,Q);return;case"Output":for(let m of I(j))B(m,Q);return;case"If":case"IfAsync":{if(B(j.cond,Q),C(j.body,Q),zh(j.else_))C(j.else_,Q);return}case"For":case"AsyncEach":case"AsyncAll":{let m=B(j.arr,Q),G=W(Q);V(G,"loop",S);let u=j.name;if(u.typename==="Symbol"){let M=u.value;V(G,M,Q2(m,M))}else d(u,S,G);if(C(j.body,G),zh(j.else_))C(j.else_,Q);return}case"Set":{let m=j.targets.filter(zh),G=S;if(zh(j.value))G=B(j.value,Q);else if(zh(j.body))B(j.body,Q);for(let u of m){let M=u.value;V(Q,M,G.tag==="typed"&&m.length===1?{...G,path:M}:S)}return}case"Macro":V(Q,String(j.name.value),S),g(j,Q);return;case"Include":F("include",j.template,Q,(m,G)=>({...W(m),seen:[...m.seen,G]}),j.ignoreMissing===!0);return;case"Import":case"FromImport":{let m=j.withContext===!0;if(F("import",j.template,Q,(G,u)=>({frames:[new Map],root:m?H:[],seen:[...G.seen,u]})),j.typename==="Import")V(Q,String(j.target.value),S);else for(let G of I(j.names)){let u=G.typename==="Pair"?G.value:G;V(Q,String(u.value),S)}return}case"Extends":F("extends",j.template,Q,(m,G)=>({frames:[new Map],root:H,seen:[...m.seen,G]}));return;case"Block":C(j.body,Q);return;case"Switch":{B(j.expr,Q);for(let m of I(j.cases))B(m.cond,Q),C(m.body,Q);if(zh(j.default))C(j.default,Q);return}default:B(j,Q)}}let Y;try{Y=Lh(h)}catch(j){return[{code:$h,path:j.message}]}return C(Y,{frames:[new Map],root:H,seen:[]}),$.push(...nh(z,K,q)),$}function w2(h,H){if(H.includes("."))return!1;if(!H.startsWith($2))return!1;for(let q=h.length-1;q>=0;q--)for(let $ of h[q])if(H===ah($.name))return!0;return!1}function V2(h,H){return h&&H===kh}function d2(h,H){return h.find((q)=>q.name===H)}function $q(h,H){let q=H.split("."),$;for(let Z=h.length-1;Z>=0;Z--){let z=d2(h[Z],q[0]);if(z){$=z;break}}for(let Z=1;$&&ZH[0]===Zq).map((H)=>[H[1],H[2],H[3]])}function Kq(h){return Th(h).some((H)=>H[0]===bq)}function _h(h,H){if(!Kq(h))return;return H??B3(h)[0]?.[0]}function Xq(h){return Th(h).filter((H)=>H[0]===zq).map((H)=>[H[2],H[3]])}function G2(h,H){let q="",$=0;for(let[Z,z]of Xq(H))q+=h.slice($,Z),$=z;return q+h.slice($)}function Wq(h){return/^(?:Unopened|Unclosed) section "(.*)" at \d+$/.exec(h instanceof Error?h.message:"")?.[1]}function u2(h){return C2(h)}function B2(h,H,q){if(q?.engine===e)return j2(h,H,q);let $=[],Z=q?.provider,z=H,K=new Set,b=[h];function J(y,w,v,l=!1){let k=w.length===1&&w[0]===z;for(let D of y){let g=D[0],F=D[1];switch(g){case"name":case"&":case"{":{if(F===".")break;if(k)K.add(F.split(".")[0]);if(!m2(w,F)&&!w2(w,F)&&!V2(l,F))$.push({code:R,path:F});break}case"#":case"^":{let d=Array.isArray(D[4])?D[4]:[];if(F==="."){J(d,w,v,l);break}if(k)K.add(F.split(".")[0]);let B=m2(w,F);if(!B){if(V2(l,F)){J(d,w,v,l);break}if(w2(w,F)){J(d,w,v,l);break}$.push({code:R,path:F});break}let C=g==="#"&&B.fields!==void 0,Y=g==="#"&&B.isArray===!0;J(d,C?[...w,B.fields]:w,v,Y?B.fields!==void 0:l);break}case">":{if(!Z)break;if(v.includes(F)||v.length>=t)break;let d=Z.resolve(F);if(d===void 0){$.push({code:Uh,path:F});break}if(qh(Z,F,gh)){$.push({code:xh,path:F});break}let B=y2(d);if(!Array.isArray(B)){$.push(B);break}let C=_h(B,F);if(C!==void 0)$.push({code:$h,path:C});b.push(G2(d,B)),J(B,w,[...v,F],l);break}default:break}}}let V=y2(h);if(!Array.isArray(V))return[V];let W=_h(V,void 0);if(W!==void 0)$.push({code:$h,path:W});return b[0]=G2(h,V),J(V,[z],[]),$.push(...nh(K,b,q)),$}var Jq=new Set(["Include","Import","FromImport","Extends"]);function v2(h,H){if(Jq.has(h.typename)){let q=h.template;if(q.typename==="Literal"&&typeof q.value==="string")H.push({ref:Nh(q.value),optional:h.ignoreMissing===!0})}for(let q of I(h))v2(q,H)}function D2(h,H,q){let $=[];v2(Lh(h),$);for(let{ref:Z,optional:z}of $){if(q.includes(Z))throw Error(`partial cycle: ${[...q,Z].join(" -> ")}`);if(q.length>=t)throw Error(`partial depth exceeded ${t}: ${Z}`);let K=H.resolve(Z);if(K===void 0){if(z)continue;throw Error(`unresolved partial: ${Z}`)}if(qh(H,Z,e))throw Error(th(Z,e));D2(K,H,[...q,Z])}}function F2(h,H,q,$,Z){return D2(h,$,H!==void 0?[H]:[]),W2(h,typeof q==="object"&&q!==null?q:{},$,Z)}function Y2(h,H,q,$){let Z=u2(h);if(_h(Z,$)!==void 0)throw Error("a template that uses partials cannot also change delimiters ({{=<% %>=}})");let z=B3(Z);if(z.length===0)return h;let K="",b=0;for(let[J,V,W]of z){if(q.includes(J))throw Error(`partial cycle: ${[...q,J].join(" -> ")}`);if(q.length>=t)throw Error(`partial depth exceeded ${t}: ${J}`);let y=H.resolve(J);if(y===void 0)throw Error(`unresolved partial: ${J}`);if(qh(H,J,gh))throw Error(th(J,gh));K+=h.slice(b,V)+Y2(y,H,[...q,J],J),b=W}return K+h.slice(b)}function v3(h){let H=h.template??(h.ref!==void 0?h.provider.resolve(h.ref):void 0);if(H===void 0)throw Error(`unresolved ref: ${h.ref??"(none)"}`);let q=X2(h.provider,h.template===void 0?h.ref:void 0,h.engine);if(h.verify!==void 0){let z=B2(H,h.verify,{provider:h.provider,engine:q}).filter((K)=>K.code!==G3);if(z.length>0)throw Error(`render verify failed: ${z.map((K)=>`${K.code} (${K.path})`).join(", ")}`)}let $=q2[h.format??"text"],Z=q===e?F2(H,h.template===void 0?h.ref:void 0,h.payload,h.provider,$):jq(H,h,$);if(h.maxChars!==void 0&&Z.length>h.maxChars)throw Error(`render exceeded maxChars budget: ${Z.length} > ${h.maxChars}`);return Z}function Qq(){let h=Hh.Writer.prototype,H={escapedValue:h.escapedValue,unescapedValue:h.unescapedValue};for(let q of["escapedValue","unescapedValue"]){let $=H[q];h[q]=function(Z,z,...K){let b=String(Z[1]);if(z.lookup(b)===void 0)throw Error(`render verify failed: ${R} (${b})`);return $.call(this,Z,z,...K)}}return()=>{h.escapedValue=H.escapedValue,h.unescapedValue=H.unescapedValue}}function jq(h,H,q){let $=Y2(h,H.provider,H.ref!==void 0?[H.ref]:[]),Z=Hh.escape;Hh.escape=(b)=>q(typeof b==="string"?b:String(b));let z,K=Qq();try{z=Hh.render($,z2(H.payload),{})}finally{Hh.escape=Z,K()}return z}class Eh{map;engine;constructor(h,H={}){this.map=h;this.engine=H.engine}resolve(h){return Object.prototype.hasOwnProperty.call(this.map,h)?this.map[h]:void 0}engineOf(h){return this.resolve(h)===void 0?void 0:this.engine}}var rh="object",oh="field";var eh="identity",h3="relationship",M2="layout",k2="source",D3="origin",H3="template",F3="index",bh="requirement",fh="dimension",Oh="measure",Ph="segment";var Wh="description",l2="summary";var Ch="string";var g2="currency",Ah="enum",U2="uuid",S2="uri",x2="inet",L2="duration";var Y3="required";var M3="default",k3="maxLength";var N2="filterable",f2="sortable";var q3="objectRef";var l3="values";var g3="fields";var U3="references";var S3="entity",O2="value",P2="projection",A2="report";var $3="from",I2="dimensions",R2="measures",i2="segment",x3="filter",c2="spine";var N="eq",P="ne",n="gt",_="gte",T="lt",E="lte",A="in",L3="like",f="isNull";var R1={string:[N,P,A,L3,f],[Ah]:[N,P,A,L3,f],int:[N,P,n,_,T,E,A,f],long:[N,P,n,_,T,E,A,f],double:[N,P,n,_,T,E,A,f],float:[N,P,n,_,T,E,A,f],decimal:[N,P,n,_,T,E,A,f],[g2]:[N,P,n,_,T,E,A,f],boolean:[N,f],date:[N,P,n,_,T,E,A,f],time:[N,P,n,_,T,E,A,f],timestamp:[N,P,n,_,T,E,A,f],[U2]:[N,P,A,f],[S2]:[N,P,A,L3,f],[x2]:[N,P,A,f],[L2]:[N,P,n,_,T,E,A,f]};var wq="association",Vq="aggregation",dq="composition";var p2="cardinality",s2="objectRef",a2="through";var p1={[dq]:"cascade",[Vq]:"set-null",[wq]:"restrict"};var i="functional",Jh="architectural";var Z3="disposition",t2="trackedBy",uh="statement",n2="counterexample";var Qh="planned",Ih="live",N3="partial",f3="retired",_2=["planned","live","partial","retired"];var T2=["planned","partial"];var O3=3,P3=4;var z3="from";var E2="agg",b3="of",A3="via",I3="filter";var R3="expr";var mq=["count","sum","avg","min","max"];var r2="any",o2="all",yq="collect",E1=[...mq,r2,o2,yq];var e2="of",hH="via",HH="grains",qH="agg";var i3="filter",$H="segment",ZH="numerator",zH="denominator";var c3="default";var bH="column";var Gq="uuid",Cq="jsonb";var uq="text",Bq="varchar",vq="character varying";var Z5={[Gq]:[Ch],[Cq]:[Ch],[uq]:[Ch],[Bq]:[Ch],[vq]:[Ch]};var KH="table",XH="view";var WH="kind";var JH="view";var p3="pageSize",QH="defaultSortField",s3="defaultSortOrder";var jH="columns";var a3="prompt";var Rh="payloadRef",wH="textRef",K3="format";var X3="responseRef",VH="maxTokens";var dH="model";var mH="promptStyle";var yH="responseFormat";var jh=[Ih,N3,Qh,f3].filter((h)=>_2.includes(h)),t3={[Ih]:"●",[N3]:"◐",[Qh]:"○",[f3]:"⊘"},GH=(h,H)=>hH?1:0;class n3{view;byId=new Map;kids=new Map;objects=[];templates=[];others=[];requirements=[];reqById=new Map;topRequirements=[];packages;topOf=new Map;constructor(h){this.view=h;for(let H of h.nodes){let q=this.file(H,H.package,void 0);this.topOf.set(H.id,H);for(let $ of H.memberGroups)for(let Z of $.members)this.fileMember(Z,H.package,q.id);if(H.type===rh)this.objects.push(q);else if(H.type===H3)this.templates.push(q);else if(H.type!==bh)this.others.push(q)}for(let H of this.kids.values())H.sort((q,$)=>q.order-$.order||GH(q.id,$.id));this.packages=h.packages.map((H)=>H.name);for(let H of h.requirements){let q=this.byId.get(H.id);if(q===void 0)continue;let $=H.parent!==null?this.reqById.get(H.parent.id):void 0,Z={node:q,req:H,...$!==void 0?{parent:$}:{},children:[],...H.level!==null?{level:H.level}:{},status:H.status,kind:H.subType};if(this.requirements.push(Z),this.reqById.set(H.id,Z),$!==void 0)$.children.push(Z);else this.topRequirements.push(Z)}}file(h,H,q){let $={};for(let K of h.attrs)$[K.name]=K.value;let Z="declaredOn"in h?h.declaredOn:null,z={id:h.id,type:h.type,subType:h.subType,name:h.name,package:H,order:h.order,...q!==void 0?{parent:q}:{},path:h.path,anchor:"anchor"in h?h.anchor:"",...h.extends!==null&&!h.extends.unresolved?{extends:h.extends.id}:{},abstract:h.abstract,isArray:"isArray"in h?h.isArray:!1,...Z!==null&&!Z.unresolved?{inheritedFrom:Z.id}:{},attrs:$,view:h};if(this.byId.set(z.id,z),q!==void 0)this.kids.set(q,[...this.kids.get(q)??[],z]);return z}fileMember(h,H,q){this.file(h,H,q);for(let $ of h.memberGroups)for(let Z of $.members)this.fileMember(Z,H,h.id)}children(h){return this.kids.get(h)??[]}ownerOf(h){let H=this.byId.get(h);while(H?.parent!==void 0)H=this.byId.get(H.parent);return H?.id??h}top(h){return this.topOf.get(h)}fields(h){return this.children(h).filter((H)=>H.type===oh)}source(h){return this.children(h).find((H)=>H.type===k2)}storage(h){let H=this.source(h);if(H===void 0)return;let q=H.attrs[XH],$=H.attrs[KH],Z=H.attrs[WH]===JH||typeof q==="string",z=typeof q==="string"?q:typeof $==="string"?$:void 0;return{kind:Z?"view":"table",...z!==void 0?{name:z}:{}}}isEntity(h){return h.type===rh&&h.subType===S3}isPrompt(h){return h.type===H3&&h.subType===a3}kindOf(h){if(h.type===H3)return h.subType===a3?"prompt":"template";if(h.type!==rh)return"other";if(h.subType===S3)return"entity";if(h.subType===O2)return"value";if(h.subType===P2)return"projection";if(h.subType===A2)return"report";return"object"}storedEntities(){return this.objects.filter((h)=>this.isEntity(h)&&!h.abstract)}claims(h){let H=this.byId.get(h)?.view;if(H===void 0)return[];return H.claims.flatMap((q)=>{let $=this.reqById.get(q.requirement.id);return $===void 0?[]:[{req:$,...q.member!==""?{member:q.member}:{}}]})}generated(h){return(this.topOf.get(h)?.files??[]).flatMap((H)=>H.paths.map((q)=>({path:q,generatedBy:H.generatedBy})))}routes(h){return this.topOf.get(h)?.routes??[]}hasRequirements(){return this.requirements.length>0}hasClaims(){return this.view.counts.claims>0}subtree(h){let H=[],q=($)=>{H.push($);for(let Z of $.children)q(Z)};return q(h),H}below(h){return this.subtree(h).slice(1)}rollup(h){let H={};for(let q of h.req.rollup)if(q.count>0)H[q.status]=q.count;return H}targetsOf(h){return h.req.targets.map((H)=>H.id)}linkTargets(h){return h.req.implementedBy.filter((H)=>H.resolves&&this.byId.has(H.target.id)).map((H)=>H.target.id)}featureOf(h){let H=new Map;for(let $ of this.claims(h)){let Z=$.req;while(Z.parent!==void 0)Z=Z.parent;if(Z.kind!==i)continue;H.set(Z,(H.get(Z)??0)+1)}let q;for(let $ of this.features()){let Z=H.get($)??0;if(Z>0&&(q===void 0||Z>(H.get(q)??0)))q=$}return q}features(){return this.topRequirements.filter((h)=>h.kind===i)}qualities(){return this.topRequirements.filter((h)=>h.kind===Jh)}claimStatus(h){let H=this.claims(h);if(H.length===0)return"unclaimed";for(let q of jh)if(H.some(($)=>$.req.status===q))return q;return"unclaimed"}modelEdges(){let h=[],H=new Set;for(let q of this.view.nodes){if(q.type===bh)continue;for(let $ of q.refs){let Z=this.ownerOf($.target.id),z=this.byId.get(Z);if(Z===q.id||z===void 0||z.type===bh)continue;let K=`${$.attr}\x00${q.id}\x00${Z}`;if(H.has(K))continue;H.add(K),h.push({kind:$.attr,from:q.id,to:Z,...$.via!==null?{via:$.via.id}:{}})}}return h.sort((q,$)=>GH(`${q.kind}\x00${q.from}\x00${q.to}`,`${$.kind}\x00${$.from}\x00${$.to}`))}slice(h){return this.view.slices.find((H)=>H.id===h)}}function X(h){return String(h??"").replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H])}function a(h){if(h==="")return"";return`${t3[h]??""} ${X(h)}`}function W3(h){if(h==="")return"";return`${t3[h]??""}`}function r(h){return h.level!==void 0?`L${h.level}`:'—'}var Bh="gate";function J3(h){let H=h.req.diagnostics.filter((z)=>z.source===Bh);if(H.length===0)return"";let q=H.some((z)=>z.severity==="error")?"error":"warn",$=H.map((z)=>z.code).join(", "),Z=H.length;return`${q==="error"?"✕":"!"} ${Z} gate ${q==="error"?Z===1?"error":"errors":Z===1?"warning":"warnings"}`}function _3(h){let H=h.node.attrs[Z3];return typeof H==="string"?`${X(H)}`:""}function ih(h){let H=jh.reduce((Z,z)=>Z+(h[z]??0),0),q=jh.filter((Z)=>(h[Z]??0)>0).map((Z)=>`${h[Z]} ${Z}`).join(", ");if(H===0)return'
    ';let $=jh.filter((Z)=>(h[Z]??0)>0).map((Z)=>``).join("");return``}function Dq(h){return`${(Math.round(h*1e4)/100).toString()}%`}function CH(h){return`
    ${jh.map(($)=>a($)).join("")}${h?'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 U(h,H){let q=h.split("/").length-1;return"../".repeat(q)+H}var j3="index.html",Vh="map.html",dh="requirements/features.html",ch="requirements/qualities.html",w3="matrix.html",ph="trace.html",Dh="prompts.html",Fh="api.html",sh="gaps.html",vh="model/index.html",Fq=new Set([oh,eh,F3,h3,fh,Oh,Ph]),Yq=new Set(["ERR_REQUIREMENT_BAD_LEVEL","ERR_REQUIREMENT_LEVEL_NESTING","ERR_REQUIREMENT_LINK_ABOVE_FLOOR"]),Mq="WARN_REQUIREMENT_OBJECT_UNCLAIMED",wh=(h,H)=>hH?1:0,x=(h)=>typeof h==="string"?h:void 0,o=(h)=>Array.isArray(h)?h.filter((H)=>typeof H==="string"):typeof h==="string"?[h]:[];function kq(h){return h===""?"-root":h.split("::").join("/")}function Kh(h){let H=h.lastIndexOf("::");return H<0?h:h.slice(H+2)}class E3{ix;constructor(h){this.ix=h}objectPage(h){return h.path}packagePage(h){return`model/${kq(h)}/index.html`}reqPage(h){return h.req.path}reqPath(h){return h.req.address}reqLabel(h){return h.req.label}pageOf(h){let H=this.ix.byId.get(h)?.path;return H===void 0||H===""?void 0:H}implLinks(h){return h.req.implementedBy.map((H)=>({ref:H.ref,resolves:H.resolves,...H.resolves&&this.ix.byId.has(H.target.id)?{target:H.target.id}:{}}))}attrValues(h,H){return h.view.attrs.find((q)=>q.name===H)?.values??[]}refLinks(h,H){return this.attrValues(h,H).flatMap((q)=>q.link!==null&&!q.link.unresolved?[q.link]:[])}refHtml(h,H,q,$){return this.attrValues(H,q).filter((Z)=>Z.link!==null).map((Z)=>this.viewLink(h,Z.link,$?.(Z.text))).join(", ")}viewLink(h,H,q){return H.unresolved?`${X(q??Kh(H.label))} (unresolved)`:this.link(h,H.id,q)}memberAnchors(h,H){return this.ix.children(h.id).filter((q)=>!H.has(q.type)&&q.anchor!=="").map((q)=>``).join("")}kindClass(h){return`k-${this.ix.kindOf(h)}`}link(h,H,q){let $=this.pageOf(H),Z=this.ix.byId.get(this.ix.ownerOf(H));if($===void 0||Z===void 0)return`${X(q??Kh(H))} (unresolved)`;let z=this.ix.reqById.get(H),K=q??(z!==void 0?this.reqLabel(z):H===Z.id?Z.name:`${Z.name}.${H.slice(Z.id.length+1)}`);return`${X(K)}`}reqLink(h,H){return`${X(this.reqLabel(H))}`}description(h){return X(x(h.attrs[Wh])??x(h.attrs[l2])??"")}topOf(h){let H=h;while(H.parent!==void 0)H=H.parent;return H}overview(h){let H=this.ix,q=j3,$=H.storedEntities(),Z=H.objects.filter((w)=>H.isEntity(w)&&w.abstract===!0).length,z=H.templates.filter((w)=>H.isPrompt(w)),K=H.objects.filter((w)=>H.kindOf(w)==="value").length,b=H.objects.filter((w)=>H.kindOf(w)==="projection").length,J=H.objects.filter((w)=>H.kindOf(w)==="report").length,V=H.view.counts,W=[];if(W.push({n:`${$.length}`,l:`stored entities${Z>0?` (${Z} abstract base${Z===1?"":"s"})`:""}`,href:U(q,Vh)}),W.push({n:`${z.length}`,l:`declared prompt${z.length===1?"":"s"}, ${T3(K,"payload or reply type","payload and reply types")}`,href:U(q,Dh)}),H.hasRequirements())W.push({n:`${V.requirements}`,l:`requirements: ${T3(V.functional,"feature")}, ${T3(V.architectural,"quality","qualities")}`,href:U(q,dh)});else W.push({n:`${b+J}`,l:`read models: ${b} projection${b===1?"":"s"}, ${J} report${J===1?"":"s"}`,href:U(q,vh)});if(V.coverageMeasured&&V.entitiesTotal>0)W.push({n:`${V.entitiesClaimed}/${V.entitiesTotal}`,l:"entities claimed by a requirement (gate)",href:U(q,sh)});else W.push({n:`${H.packages.length}`,l:`package${H.packages.length===1?"":"s"} in the model`,href:U(q,vh)});if(H.view.sources.routes){let w=H.objects.filter((v)=>H.routes(v.id).length>0).length;W.push({n:`${w}`,l:"objects with mounted REST routes",href:U(q,Fh)})}else W.push({n:"—",l:"REST routes: none recorded by this run",href:U(q,Fh)});W.push({n:H.view.sources.files?`${V.files}`:"—",l:H.view.sources.files?"generated files traced to a node":"generated files: no manifest read",href:U(q,ph)});let y=["the effective model"];if(H.view.sources.requirements)y.push("the requirement gate's ledger");if(H.view.sources.files)y.push("the generation manifest");return{heading:X(`What ${h} does`),sourcesLine:X(lq(y)),tiles:W.map((w)=>({n:X(w.n),l:X(w.l),href:X(w.href)})),hasRequirements:H.hasRequirements(),featureCards:H.features().map((w)=>this.capCard(q,w)),qualityCards:H.qualities().map((w)=>this.capCard(q,w)),hasFeatures:H.features().length>0,hasQualities:H.qualities().length>0,packageCards:H.packages.map((w)=>this.packageCard(q,w))}}capCard(h,H){let q=this.ix.below(H).length,$=this.ix.targetsOf(H).length;return{levelHtml:r(H),linkHtml:this.reqLink(h,H),statusHtml:a(H.status),verdictHtml:J3(H),statement:X(x(H.node.attrs[uh])??""),barHtml:ih(this.ix.rollup(H)),countsLine:X(`${q} requirement${q===1?"":"s"} below · ${$} model node${$===1?"":"s"} claimed`),children:H.children.map((Z)=>({levelHtml:r(Z),linkHtml:this.reqLink(h,Z),glyphHtml:W3(Z.status)})),hasChildren:H.children.length>0}}packageCard(h,H){let q=[...this.ix.objects,...this.ix.templates,...this.ix.others].filter((b)=>b.package===H),$=new Map;for(let b of q)$.set(this.ix.kindOf(b),($.get(this.ix.kindOf(b))??0)+1);let z=["entity","value","projection","report","prompt","template","object","other"].filter((b)=>$.has(b)).map((b)=>`● ${$.get(b)} ${gq(b,$.get(b)??0)}`).join(" · "),K=q.slice(0,12);return{name:X(H===""?"(no package)":H),href:X(U(h,this.packagePage(H))),kindLineHtml:z,membersHtml:K.map((b)=>this.link(h,b.id)).join(", ")+(q.length>K.length?` +${q.length-K.length}`:"")}}map(){let h=this.ix,H=[],q=[{value:"",label:"Whole model"}];if(h.templates.some(($)=>h.isPrompt($)))q.push({value:"@prompts",label:"Prompts and their payloads"});H.push({label:"Model",options:q});for(let $ of h.topRequirements){let Z=[];for(let z of[$,...$.children]){let K=h.slice(`requirement:${z.node.id}`);if(K===void 0)continue;let b=z===$?"":" ";Z.push({value:K.id,label:`${b}${z.level!==void 0?`L${z.level} `:""}${this.reqLabel(z)} (${h.targetsOf(z).length})`})}if(Z.length>0)H.push({label:`${$.kind===i?"Feature":"Quality"}: ${this.reqLabel($)}`,options:Z})}if(h.packages.length>1)H.push({label:"Package",options:h.packages.map(($)=>({value:`package:${$}`,label:$===""?"(no package)":$}))});return{sliceGroups:H.map(($)=>({label:X($.label),options:$.options.map((Z)=>({value:X(Z.value),label:X(Z.label)}))})),hasRequirements:h.hasRequirements()}}object(h){let H=this.ix,q=this.objectPage(h),$=H.kindOf(h),Z=H.claims(h.id),z=H.storage(h.id),K=z===void 0?$==="value"?"value object: no storage":"no source":`${z.kind}${z.name!==void 0?` ${z.name}`:""}`,b=H.fields(h.id).map((d)=>this.fieldRow(q,h,d)),J=b.some((d)=>d.column!==""),V=H.children(h.id).filter((d)=>d.type===eh||d.type===F3||d.type===h3).map((d)=>this.keyRow(q,d)),W=H.children(h.id).filter((d)=>d.type===fh||d.type===Oh||d.type===Ph).map((d)=>this.reportingRow(q,d)),y=H.children(h.id).filter((d)=>d.type===M2).map((d)=>this.layoutRow(d)),w=this.unclaimedEntity(h),v=this.whyRows(q,h),l=H.top(h.id)?.referencedBy??[],k=(d)=>d===Rh||d===X3,D=[...new Set(l.filter((d)=>k(d.attr)).map((d)=>d.from.id))].sort(wh).map((d)=>this.link(q,d)),g=[...new Set(l.filter((d)=>!k(d.attr)).map((d)=>d.from.id))].sort(wh).map((d)=>this.link(q,d)),F=h.extends!==void 0?this.link(q,h.extends):"";return{id:X(h.id),name:X(h.name),kindLabel:X(`object.${h.subType}`),crumbsHtml:`Model › ${X(h.package===""?"(no package)":h.package)} › object.${X(h.subType)}${this.memberAnchors(h,Fq)}`,isAbstract:h.abstract===!0,isUnclaimed:w,isReadOnly:z?.kind==="view",kindBadge:X($),description:this.description(h),storageLine:X(K),extendsHtml:F,whyRows:v,hasWhy:v.length>0,whyEmptyHtml:this.whyEmpty(h),fields:b,hasFields:b.length>0,hasColumn:J,showClaims:this.ix.hasRequirements(),keys:V,hasKeys:V.length>0,reporting:W,hasReporting:W.length>0,layouts:y,hasLayouts:y.length>0,projection:$==="projection"?this.projectionBlock(q,h):void 0,report:$==="report"?this.reportBlock(q,h):void 0,routes:H.routes(h.id).map((d)=>({method:X(d.method),path:X(d.path)})),hasRoutes:H.routes(h.id).length>0,routesNote:!H.view.sources.routes?"This run recorded no routes.":"No generated routes are mounted for it.",usedByHtml:D.join(", "),referencedByHtml:g.join(", "),generated:this.generatedGroups(h.id),hasGenerated:H.generated(h.id).length>0,generatedNote:!H.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",claimCount:Z.length}}unclaimedEntity(h){let H=this.ix;if(!H.isEntity(h)||h.abstract===!0)return!1;return H.top(h.id)?.unclaimed===!0}whyRows(h,H){let q=[...this.ix.claims(H.id)].sort((z,K)=>this.ix.requirements.indexOf(z.req)-this.ix.requirements.indexOf(K.req)),$=[],Z;for(let z of q){let K=this.topOf(z.req);$.push({capabilityHtml:K===Z?"":this.reqLink(h,K),reqHtml:this.reqLink(h,z.req),statement:X(x(z.req.node.attrs[uh])??""),levelHtml:r(z.req),statusHtml:a(z.req.status),onHtml:z.member!==void 0?`${X(z.member)}`:'whole object'}),Z=K}return $}whyEmpty(h){if(!this.ix.hasRequirements())return`This model declares no requirements, so nothing states why ${X(h.name)} exists.`;if(this.unclaimedEntity(h))return`No requirement claims ${X(h.name)}. The gate reports this as ${Mq}.`;return`No requirement claims ${X(h.name)}.`}fieldRow(h,H,q){let $=this.refHtml(h,q,q3),Z=q.subType===Ah?o(q.attrs[l3]):[],z=[];if(q.attrs[Y3]===!0)z.push("required");if(q.attrs[N2]===!0)z.push("filterable");if(q.attrs[f2]===!0)z.push("sortable");if(q.attrs[k3]!==void 0)z.push(`max ${String(q.attrs[k3])}`);if(q.attrs[M3]!==void 0)z.push(`default ${Xh(q.attrs[M3])}`);if(this.ix.children(q.id).some((b)=>b.type===D3))z.push("derived");let K=this.ix.claims(H.id).filter((b)=>b.member!==void 0&&b.member.split(".")[0]===q.name);return{anchor:X(q.anchor),name:X(q.name),inheritedHtml:q.inheritedFrom!==void 0?`inherited`:"",type:X(`${q.subType}${q.isArray===!0?"[]":""}`),refHtml:$!==""?` → ${$}`:"",valuesHtml:Z.length>0?`
    ${Z.map(X).join(" | ")}
    `:"",column:X(x(q.attrs[bH])??""),flagsHtml:z.map((b)=>`${X(b)}`).join(""),claimsHtml:K.map((b)=>`${W3(b.req.status)} ${X(this.reqLabel(b.req))}`).join("
    ")}}keyRow(h,H){let q=o(H.attrs[g3]),$=this.refHtml(h,H,U3)||this.refHtml(h,H,s2),Z=x(H.attrs[a2]),z=x(H.attrs[p2]),K=H.type===h3?[z,Z!==void 0?`through ${Kh(Z)}`:void 0].filter((b)=>b!==void 0).join(", "):`(${q.join(", ")})`;return{anchor:X(H.anchor),kind:X(`${H.type}.${H.subType}`),name:X(H.name),inheritedHtml:H.inheritedFrom!==void 0?'inherited':"",shape:X(K),targetHtml:$!==""?`→ ${$}`:""}}reportingRow(h,H){let q=H.attrs,$=[],Z=x(q[qH]),z=this.refHtml(h,H,e2,Kh);if(Z!==void 0)$.push(`${X(Z)}(${z})`);else if(z!=="")$.push(`of ${z}`);let K=x(q[ZH]),b=x(q[zH]);if(K!==void 0&&b!==void 0)$.push(`${X(K)} ÷ ${X(b)}`);let J=x(q[hH]);if(J!==void 0)$.push(`via ${X(Kh(J))}`);let V=o(q[HH]);if(V.length>0)$.push(`grains ${V.map((y)=>`${X(y)}`).join(" ")}`);let W=x(q[$H]);if(W!==void 0)$.push(`segment ${X(W)}`);if(q[i3]!==void 0)$.push(`filter ${X(Xh(q[i3]))}`);if(q[c3]!==void 0)$.push(`default ${X(Xh(q[c3]))}`);return{anchor:X(H.anchor),kind:X(`${H.type}.${H.subType}`),name:X(H.name),definitionHtml:$.join(" · ")}}layoutRow(h){let H=[],q=o(h.attrs[jH]);if(q.length>0)H.push(`columns ${q.map((Z)=>`${X(Z)}`).join(", ")}`);let $=x(h.attrs[QH]);if($!==void 0)H.push(`sorted by ${X($)}${x(h.attrs[s3])!==void 0?` ${X(x(h.attrs[s3]))}`:""}`);if(typeof h.attrs[p3]==="number")H.push(`${h.attrs[p3]} per page`);return{kind:X(`${h.type}.${h.subType}`),name:X(h.name),detailHtml:H.join(", ")}}projectionBlock(h,H){let q=this.ix,$=[],Z=new Set;for(let z of q.fields(H.id)){if(z.extends!==void 0)Z.add(q.ownerOf(z.extends));for(let K of q.children(z.id).filter((b)=>b.type===D3)){let b=this.originDefinition(h,K);for(let J of this.refLinks(K,z3))Z.add(q.ownerOf(J.id));$.push({field:X(z.name),origin:X(`origin.${K.subType}`),definitionHtml:b})}}return{basesHtml:[...Z].filter((z)=>z!==H.id).sort(wh).map((z)=>this.link(h,z)).join(", "),origins:$,hasOrigins:$.length>0}}originDefinition(h,H){let q=H.attrs,$=(K)=>this.attrValues(H,K).map((b)=>b.link!==null&&!b.link.unresolved?this.link(h,b.link.id,Kh(b.text)):`${X(Kh(b.text))}`).join(", "),Z=[],z=x(q[E2]);if(z!==void 0)Z.push(`${X(z)}(${$(b3)})`);else if(q[b3]!==void 0)Z.push(`of ${$(b3)}`);if(q[z3]!==void 0)Z.push(`from ${$(z3)}`);if(q[A3]!==void 0)Z.push(`via ${X(Kh(String(q[A3])))}`);if(q[R3]!==void 0)Z.push(`${X(Xh(q[R3]))}`);if(q[I3]!==void 0)Z.push(`filter ${X(Xh(q[I3]))}`);return Z.join(" · ")}reportBlock(h,H){let q=H.attrs,$=this.refLinks(H,$3)[0]?.id??x(q[$3]),Z=(K,b)=>{let V=[$!==void 0?`${$}.${K}`:void 0,`${H.package===""?"":`${H.package}::`}${K}`].filter((W)=>W!==void 0).find((W)=>this.ix.byId.get(W)?.type===b||this.ix.byId.has(W)&&K.includes("."));return V!==void 0?this.link(h,V,K):`${X(K)}`},z=x(q[c2]);return{fromHtml:this.refHtml(h,H,$3),spineHtml:z!==void 0?`${X(z)}`:"",dimensionsHtml:o(q[I2]).map((K)=>Z(K,fh)).join(", "),measuresHtml:o(q[R2]).map((K)=>Z(K,Oh)).join(", "),segmentHtml:o(q[i2]).map((K)=>Z(K,Ph)).join(", "),filterHtml:q[x3]!==void 0?`${X(Xh(q[x3]))}`:""}}generatedGroups(h){let H=new Map;for(let q of this.ix.generated(h))H.set(q.generatedBy,[...H.get(q.generatedBy)??[],q.path]);return[...H.keys()].sort(wh).map((q)=>({generator:X(q),files:(H.get(q)??[]).map(($)=>X($))}))}node(h){let H=this.ix,q=this.objectPage(h),$=`${h.type}.${h.subType}`,Z=this.whyRows(q,h),z=this.attrRows(q,h),K=[...(H.top(h.id)?.referencedBy??[]).map((J)=>J.from.id),...H.claims(h.id).map((J)=>this.topOf(J.req).node.id)],b=[...new Set(K.filter((J)=>J!==h.id))].sort(wh).map((J)=>this.link(q,J));return{id:X(h.id),name:X(h.name),kindLabel:X($),crumbsHtml:`Model › ${X(h.package===""?"(no package)":h.package)} › ${X($)}`,isAbstract:h.abstract===!0,description:this.description(h),extendsHtml:h.extends!==void 0?this.link(q,h.extends):"",attrs:z,hasAttrs:z.length>0,members:H.children(h.id).map((J)=>({anchor:X(J.anchor),kind:X(`${J.type}.${J.subType}`),nameHtml:H.reqById.has(J.id)?this.link(q,J.id):X(J.name===""?`#${J.order}`:J.name),attrsHtml:this.attrRows(q,J).map((V)=>`@${V.name} ${V.valueHtml}`).join("
    "),below:H.children(J.id).length})),hasMembers:H.children(h.id).length>0,whyRows:Z,hasWhy:Z.length>0,whyEmptyHtml:this.whyEmpty(h),referencedByHtml:b.join(", "),generated:this.generatedGroups(h.id),hasGenerated:H.generated(h.id).length>0,generatedNote:!H.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it."}}attrRows(h,H){return H.view.attrs.map((q)=>{let $=q.values.filter((Z)=>Z.link!==null&&!Z.link.unresolved);return{name:X(q.name),valueHtml:$.length>0&&$.length===q.values.length?$.map((Z)=>this.link(h,Z.link.id)).join(", "):`${X(Xh(q.value))}`}})}prompt(h,H){let q=this.ix,$=this.objectPage(h),Z=this.refLinks(h,Rh)[0]?.id,z=this.refLinks(h,X3)[0]?.id,K=H!==void 0?uH(H):void 0,b=Z!==void 0?q.byId.get(Z):void 0,J=z!==void 0?q.byId.get(z):void 0,V=b!==void 0?q.fields(b.id).map((D)=>({name:X(D.name),requiredHtml:D.attrs[Y3]===!0?'required':"",type:X(`${D.subType}${D.isArray===!0?"[]":""}`),refHtml:this.refHtml($,D,q3)!==""?` → ${this.refHtml($,D,q3)}`:"",usedHtml:K===void 0?'text not read':K.has(D.name)?"yes":'no'})):[],W=J!==void 0?q.fields(J.id).map((D)=>({name:X(D.name),type:X(`${D.subType}${D.isArray===!0?"[]":""}`),valuesHtml:D.subType===Ah?`
    ${o(D.attrs[l3]).map(X).join(" | ")}
    `:""})):[],y=x(h.attrs[wH])??"",w=H!==void 0?H.replace(/\n$/,"").split(` -`).length:0,v=[K3,yH,mH,dH,VH].filter((D)=>h.attrs[D]!==void 0).map((D)=>`@${X(D)} ${X(Xh(h.attrs[D]))}`).join(""),l=q.claims(h.id),k=this.whyRows($,h);return{name:X(h.name),kindLabel:X(`template.${h.subType}`),crumbsHtml:`Prompts › ${X(h.package===""?"(no package)":h.package)} › template.${X(h.subType)}${this.memberAnchors(h,new Set)}`,isUnclaimed:q.hasClaims()&&l.length===0,description:this.description(h),attrsHtml:v,payloadHtml:b!==void 0?this.link($,b.id):"none",payloadRows:V,hasPayload:b!==void 0,replyHtml:J!==void 0?this.link($,J.id):"none",replyRows:W,hasReply:J!==void 0,textRef:X(y),textMeta:X(H!==void 0?`${y}.mustache · ${w} line${w===1?"":"s"}${x(h.attrs[K3])!==void 0?` · ${x(h.attrs[K3])}`:""}`:`${y}.mustache`),textHtml:H!==void 0?Sq(H):"",hasText:H!==void 0,generated:this.generatedGroups(h.id),hasGenerated:q.generated(h.id).length>0,generatedNote:!q.view.sources.files?"No generation manifest was read.":"Nothing generated is traced to it.",whyRows:k,hasWhy:k.length>0,whyEmptyHtml:q.hasRequirements()?`No requirement claims ${X(h.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 h=Dh,H=this.ix.templates.map((q)=>{let $=this.refHtml(h,q,Rh),Z=this.refHtml(h,q,X3),z=this.ix.claims(q.id);return{linkHtml:this.link(h,q.id),kind:X(`template.${q.subType}`),description:this.description(q),payloadHtml:$!==""?$:'none',replyHtml:Z!==""?Z:'none (outbound only)',claimsHtml:z.length>0?z.map((K)=>a(K.req.status)).join(""):this.ix.hasClaims()?'unclaimed':'—'}});return{rows:H,hasRows:H.length>0}}requirements(h,H){let q=this.ix.topRequirements.filter((Z)=>Z.kind===h),$=q.length>0?`
      ${q.map((Z)=>this.treeNode(H,Z)).join("")}
    `:"";return{isFeatures:h===i,featuresHref:X(U(H,dh)),qualitiesHref:X(U(H,ch)),featureCount:this.ix.requirements.filter((Z)=>Z.kind===i).length,qualityCount:this.ix.requirements.filter((Z)=>Z.kind===Jh).length,treeHtml:$,hasTree:q.length>0,emptyNote:h===i?"No requirement.functional is declared.":"No requirement.architectural is declared."}}treeNode(h,H){let q=this.implLinks(H).map((z)=>{if(z.target!==void 0)return`${this.link(h,z.target,z.ref)}`;return H.status===Qh?`${X(z.ref)} (not yet)`:`${X(z.ref)} (dangling)`}),$=H.children.length>0?`${ih(this.ix.rollup(H))}`:"";return`
  • ${`
    ${r(H)}${this.reqLink(h,H)} ${a(H.status)}${_3(H)}${J3(H)}${$}${q.join("")}
    ${X(x(H.node.attrs[uh])??"")}
    `}${H.children.length>0?`
      ${H.children.map((z)=>this.treeNode(h,z)).join("")}
    `:""}
  • `}requirement(h){let H=this.ix,q=this.reqPage(h),$=[];for(let d=h;d!==void 0;d=d.parent)$.unshift(d);let Z=h.kind===i?{href:dh,label:"Features"}:{href:ch,label:"Qualities"},z=h.req.inLedger,K=h.req.diagnostics,b=this.implLinks(h),J=b.map((d)=>{let B=d.target!==void 0?H.byId.get(d.target):void 0;return{refHtml:B!==void 0?this.link(q,B.id,d.ref):`${X(d.ref)}`,kind:X(B!==void 0?`${B.type}.${B.subType}`:""),resolvesHtml:d.resolves?'resolves':h.status===Qh?'not yet (allowed on planned)':'dangling'}}),V=K.filter((d)=>d.source===Bh),W=K.filter((d)=>d.source!==Bh),y=K.some((d)=>Yq.has(d.code)),w=h.kind===i&&(h.level??0)>=P3,v=b.length===0?"none":b.every((d)=>d.resolves)?"yes":"no",l=H.below(h),k=H.slice(`requirement:${h.node.id}`),D=h;while(D!==void 0&&(D.level??0)>O3)D=D.parent;let g=o(h.node.attrs[t2]),F=this.description(h.node);return{crumbsHtml:`${Z.label} › ${$.map((d)=>d===h?X(this.reqLabel(d)):this.reqLink(q,d)).join(" › ")}`,levelHtml:r(h),name:X(this.reqLabel(h)),statusHtml:a(h.status),dispositionHtml:_3(h),verdictHtml:J3(h),address:X(`${h.req.qualifiedPath} · requirement.${h.kind}`),statement:X(x(h.node.attrs[uh])??""),counterexample:X(x(h.node.attrs[n2])??""),description:F,hasDescription:F!=="",linkRows:J,hasLinks:J.length>0,linksEmpty:h.level!==void 0&&h.levelh.children.length,hasBelow:h.children.length>0,belowBarHtml:ih(H.rollup(h)),children:h.children.map((d)=>({levelHtml:r(d),linkHtml:this.reqLink(q,d),statusHtml:a(d.status)})),sliceHref:k!==void 0?X(`${U(q,Vh)}?slice=${encodeURIComponent(k.id)}`):"",traceHref:D!==void 0?X(`${U(q,ph)}?start=${encodeURIComponent(D.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:v==="none"?'no links':v==="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:y?'no':'yes',how:"Nesting agrees with level, and links sit only at L4 and L5."},{what:"Gate findings",verdictHtml:V.length>0?`${V.length}`:z?'none':'not read',how:V.length>0?V.map((d)=>`${X(d.code)} ${X(d.message)}`).join("
    "):z?"Nothing reported for this entry.":"This build read no meta verify output."},{what:"Authoring advisories",verdictHtml:z?`${W.length}`:'not read',how:W.length>0?W.map((d)=>`${X(d.code)} ${X(d.message)}`).join("
    "):z?"None. The authoring lint never fails a build.":"This build read no meta verify output."},{what:"Test exists",verdictHtml:w?'by generator':'not by default',how:w?"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((d)=>({what:X(d.what),verdictHtml:d.verdictHtml,howHtml:d.how})),trackedHtml:g.map((d)=>`${X(d)}`).join(" "),digest:X(h.req.digest)}}matrix(){let h=this.ix,H=w3,q=h.requirements.flatMap((b)=>this.implLinks(b).flatMap((J)=>J.target!==void 0?[h.ownerOf(J.target)]:[])),$=new Set([...h.storedEntities(),...h.templates.filter((b)=>h.isPrompt(b))].map((b)=>b.id));for(let b of q)if(h.byId.get(b)?.parent===void 0&&h.byId.get(b)?.type!==bh)$.add(b);let Z=[...$].map((b)=>h.byId.get(b)).sort((b,J)=>h.claims(J.id).length-h.claims(b.id).length||wh(b.name,J.name)||wh(b.id,J.id)),z=`${Z.map((b)=>`
    ${this.link(H,b.id)}
    `).join("")}`,K=[];for(let b of h.topRequirements){let J=h.subtree(b).filter((V)=>V.req.implementedBy.length>0);if(J.length===0)continue;K.push(`${b.kind===i?"Feature":"Quality"}: ${this.reqLink(H,b)}${Z.map(()=>'').join("")}`);for(let V of J){let W=new Set(this.implLinks(V).filter((w)=>w.target!==void 0).map((w)=>h.ownerOf(w.target))),y=this.reqPath(V).split(".").slice(1).join(".")||this.reqLabel(V);K.push(`${r(V)}${X(y)}${Z.map((w)=>W.has(w.id)?`${W3(V.status)}`:'').join("")}`)}}return{tableHtml:K.length>0?`${z}${K.join("")}
    `:"",hasRows:K.length>0,hasRequirements:h.hasRequirements()}}trace(){let h=this.ix.requirements.filter((q)=>q.level!==void 0&&q.level<=O3),H=h.length===0?this.ix.topRequirements:[];return{options:[...h,...H].map((q)=>({value:X(q.node.id),label:X(`${" ".repeat(Math.max(0,(q.level??1)-1))}${q.level!==void 0?`L${q.level} `:""}${this.reqLabel(q)}`)})),hasStarts:h.length+H.length>0,hasUsage:!1}}gaps(){let h=this.ix,H=sh,q=[],$=(z,K,b,J,V)=>{q.push({title:X(z),count:X(String(K)),source:X(b),isGate:b==="meta verify",whyHtml:J,bodyHtml:V})};if(h.view.sources.requirements){let z=(w)=>[...h.requirements.flatMap((v)=>v.req.diagnostics.filter((l)=>l.source===Bh===w).map((l)=>({req:v,d:l}))),...h.view.advisories.filter((v)=>v.path===""&&v.source===Bh===w).map((v)=>({d:v}))],K=(w,v)=>w.length===0?'
    None.
    ':`${w.map(({req:l,d:k})=>``).join("")}
    ${X(k.code)}${l!==void 0?this.reqLink(H,l):""}
    ${X(k.message)}
    `,b=z(!0);$("Gate findings",b.length,"meta verify","Printed by every run of the requirement gate.",K(b,(w)=>`chip v-${w==="error"?"error":"warn"}`));let J=z(!1);$("Authoring advisories",J.length,"authoring lint","Printed beside the gate's findings, and never able to fail a build.",K(J,()=>"chip"));let V=h.storedEntities().filter((w)=>this.unclaimedEntity(w));$("Entities no requirement claims",V.length,"meta verify","The gate's coverage warning. Each is a capability nobody has written down.",V.length>0?V.map((w)=>this.link(H,w.id)).join(", "):'
    None.
    ');let W=(w)=>T2.includes(w.status),y=h.requirements.filter((w)=>W(w)&&w.node.attrs[Z3]===void 0&&!h.below(w).some(W));$("Undecided gaps",h.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.",Q3(y.map((w)=>`${r(w)}${this.reqLink(H,w)} ${a(w.status)}`)))}if(h.hasRequirements()){let z=h.requirements.filter((b)=>b.status===Qh&&h.below(b).some((J)=>J.status===Ih));$("Planned, with live work below",z.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.",Q3(z.map((b)=>`${r(b)}${this.reqLink(H,b)} ${a(b.status)} ${ih(h.rollup(b))}`)));let K=h.templates.filter((b)=>h.isPrompt(b)&&h.claims(b.id).length===0);$("Prompts no requirement claims",K.length,"explorer check","The gate counts entity coverage only. An L4 may claim a prompt.",K.length>0?K.map((b)=>this.link(H,b.id)).join(", "):'
    None.
    ')}$("Generated modules nothing imports","—","explorer check","Needs a scan of hand-written imports, which this build does not run.",'
    Not scanned.
    ');let Z=h.storedEntities().flatMap((z)=>{let K=new Set(h.children(z.id).filter((b)=>b.type===eh&&b.attrs[U3]!==void 0).flatMap((b)=>o(b.attrs[g3])));return h.fields(z.id).filter((b)=>/[a-z]Id$/.test(b.name)&&!K.has(b.name))});if($("Fields that look like references but are not declared",Z.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.",Q3(Z.map((z)=>`${this.link(H,z.id)} ${X(z.subType)}`))),h.templates.length>0){let z=this.unusedPayload();$("Payload fields the prompt text never uses",z===void 0?"—":z.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.",z===void 0?'
    No prompt text was read.
    ':Q3(z.map(({p:K,f:b})=>`${this.link(H,K.id)}: ${this.link(H,b.id,b.name)}`)))}return{cards:q}}texts=new Map;unusedPayload(){let h=[],H=!1;for(let q of this.ix.templates){let $=this.texts.get(q.id),Z=this.refLinks(q,Rh)[0]?.id;if($===void 0||Z===void 0)continue;H=!0;let z=uH($);for(let K of this.ix.fields(Z))if(!z.has(K.name))h.push({p:q,f:K})}return H?h:void 0}api(){let h=this.ix,H=Fh,q=h.objects.filter((Z)=>h.routes(Z.id).length>0).map((Z)=>({linkHtml:this.link(H,Z.id),kind:X(h.kindOf(Z)),isReadOnly:h.storage(Z.id)?.kind==="view",routes:h.routes(Z.id).map((z)=>({method:X(z.method),methodClass:X(z.method.toLowerCase()),path:X(z.path)}))})),$=q.reduce((Z,z)=>Z+z.routes.length,0);return{groups:q,hasGroups:q.length>0,recorded:h.view.sources.routes,summary:X(`${$} route${$===1?"":"s"} on ${q.length} object${q.length===1?"":"s"}`)}}model(){return{packageCards:this.ix.packages.map((h)=>this.packageCard(vh,h))}}packageIndex(h){let H=this.ix,q=this.packagePage(h),$=[...H.objects,...H.templates,...H.others].filter((Z)=>Z.package===h).map((Z)=>{let z=H.storage(Z.id),K=H.claimStatus(Z.id);return{linkHtml:this.link(q,Z.id),kind:X(`${Z.type}.${Z.subType}`),abstractHtml:Z.abstract===!0?'abstract':"",storage:X(z===void 0?"":`${z.kind}${z.name!==void 0?` ${z.name}`:""}`),fieldCount:H.fields(Z.id).length,statusHtml:K==="unclaimed"?this.unclaimedEntity(Z)?'unclaimed':"":a(K),description:this.description(Z)}});return{name:X(h===""?"(no package)":h),crumbsHtml:`Model › ${X(h===""?"(no package)":h)}`,rows:$}}}function Q3(h){return h.length===0?'
    None.
    ':`
      ${h.map((H)=>`
    • ${H}
    • `).join("")}
    `}function Xh(h){return typeof h==="string"?h:JSON.stringify(h)}function lq(h){return h.length<=1?h[0]??"":`${h.slice(0,-1).join(", ")} and ${h[h.length-1]}`}function T3(h,H,q=`${H}s`){return`${h} ${h===1?H:q}`}function gq(h,H){if(H===1)return h;return h==="entity"?"entities":`${h}s`}var Uq=/\{\{\s*([#^/&{]?)\s*([A-Za-z_][\w.]*)\s*\}?\}\}/g;function uH(h){let H=new Set;for(let q of h.matchAll(Uq))if(q[1]!=="/")H.add(q[2].split(".")[0]);return H}function Sq(h){let H="",q=0;for(let $ of h.matchAll(/\{\{[^}]*\}?\}\}/g))H+=X(h.slice(q,$.index)),H+=`${X($[0])}`,q=$.index+$[0].length;return H+X(h.slice(q))}var xq=[{key:"overview",label:"Overview",href:j3},{key:"map",label:"Model map",href:Vh},{key:"requirements",label:"Requirements",href:dh},{key:"matrix",label:"Matrix",href:w3},{key:"trace",label:"Trace",href:ph},{key:"prompts",label:"Prompts",href:Dh},{key:"api",label:"API",href:Fh},{key:"gaps",label:"Gaps",href:sh}];function Lq(h){if(h===void 0)return new Map;if(h instanceof Map)return h;return new Map(Object.entries(h))}function BH(h){let H=new n3(h.view),q=new E3(H),$=Lq(h.texts);for(let[y,w]of $)q.texts.set(y,w);let Z=(y)=>{let w=h.templates[y];if(w===void 0)throw Error(`docs-site explorer: no template ${y}`);return w},z=new Eh({card:Z("explorer-card.mustache")}),K=Z("explorer-head.mustache"),b=Z("explorer-foot.mustache"),J=CH(H.hasClaims()),V=new Map,W=(y,w,v,l,k,D=!1)=>{if(V.has(w))throw Error(`docs-site explorer: two pages map to ${w}`);let g=Z(y);V.set(w,()=>{let F=U(w,""),d={...k(),siteTitle:X(h.title),pageTitle:X(l),stamp:X(h.stamp??""),relRoot:F,assetBase:h.assetBase,cytoscapeSrc:h.cytoscapeSrc(F),graph3dSrc:h.graph3dSrc(F),needsGraph:D,pageKey:v,nav:xq.map((B)=>({label:B.label,href:U(w,B.href),on:B.key===v})),legendHtml:J};return v3({template:K+g+b,payload:d,provider:z,format:"text"})})};W("explorer-overview.html.mustache",j3,"overview","Overview",()=>q.overview(h.title)),W("explorer-map.html.mustache",Vh,"map","Model map",()=>q.map(),!0),W("explorer-requirements.html.mustache",dh,"requirements","Features",()=>q.requirements(i,dh)),W("explorer-requirements.html.mustache",ch,"requirements","Qualities",()=>q.requirements(Jh,ch)),W("explorer-matrix.html.mustache",w3,"matrix","Matrix",()=>q.matrix()),W("explorer-trace.html.mustache",ph,"trace","Trace",()=>q.trace(),!0),W("explorer-prompts.html.mustache",Dh,"prompts","Prompts",()=>q.prompts()),W("explorer-api.html.mustache",Fh,"api","API",()=>q.api()),W("explorer-gaps.html.mustache",sh,"gaps","Gaps",()=>q.gaps()),W("explorer-model.html.mustache",vh,"map","Packages",()=>q.model());for(let y of H.packages)W("explorer-package.html.mustache",q.packagePage(y),"map",y===""?"(no package)":y,()=>q.packageIndex(y));for(let y of H.objects)W("explorer-object.html.mustache",q.objectPage(y),"map",y.name,()=>q.object(y),!0);for(let y of H.templates)W("explorer-prompt.html.mustache",q.objectPage(y),"prompts",y.name,()=>q.prompt(y,$.get(y.id)));for(let y of H.others)W("explorer-node.html.mustache",q.objectPage(y),"map",y.name,()=>q.node(y));for(let y of H.requirements)W("explorer-requirement.html.mustache",q.reqPage(y),"requirements",q.reqLabel(y),()=>q.requirement(y));return{pages:V,graphData:()=>Nq(H,q)}}function Nq(h,H){let q=h.features(),$=[...h.objects,...h.templates],Z=$.map((W)=>{let y=h.featureOf(W.id),w=h.claims(W.id);return{id:W.id,name:W.name,kind:h.kindOf(W),pkg:W.package,href:H.objectPage(W),abstract:W.abstract===!0?1:0,fields:h.fields(W.id).length,claims:w.length,status:h.claimStatus(W.id),feature:y!==void 0?q.indexOf(y):-1,quality:w.length>0&&w.every((v)=>v.req.kind===Jh)?1:0,unclaimed:H.unclaimedEntity(W)?1:0,api:h.routes(W.id).map((v)=>`${v.method} ${v.path}`),gen:h.generated(W.id).length,storage:h.storage(W.id)?.kind??""}}),z=new Set($.map((W)=>W.id)),K={};for(let W of h.view.slices)K[W.id]=[...new Set(W.nodes.map((y)=>h.ownerOf(y)).filter((y)=>z.has(y)))].sort();let b=h.requirements.map((W)=>({id:W.node.id,label:H.reqLabel(W),path:H.reqPath(W),level:W.level??0,status:W.status,kind:W.kind,parent:W.parent?.node.id??"",href:H.reqPage(W),targets:h.linkTargets(W).map((y)=>h.ownerOf(y)),statement:W.req.statement,rollup:h.rollup(W),claimed:h.targetsOf(W).length})),J={};for(let W of $){let y=new Map;for(let w of h.generated(W.id))y.set(w.generatedBy,(y.get(w.generatedBy)??0)+1);if(y.size>0)J[W.id]=[...y.entries()].sort((w,v)=>w[0]v[0]?1:0)}let V=[];for(let W of $){let y=typeof W.attrs[Wh]==="string"?W.attrs[Wh]:"";V.push({t:W.name,s:`${W.type}.${W.subType}${W.package!==""?` · ${W.package}`:""}`,h:H.objectPage(W),k:`${W.name} ${W.id} ${y}`.toLowerCase()});for(let w of h.fields(W.id)){if(w.inheritedFrom!==void 0)continue;V.push({t:`${W.name}.${w.name}`,s:`field.${w.subType}`,h:H.pageOf(w.id)??H.objectPage(W),k:`${W.name}.${w.name} ${w.id}`.toLowerCase()})}}for(let W of h.others){let y=typeof W.attrs[Wh]==="string"?W.attrs[Wh]:"";V.push({t:W.name,s:`${W.type}.${W.subType}${W.package!==""?` · ${W.package}`:""}`,h:H.objectPage(W),k:`${W.name} ${W.id} ${y}`.toLowerCase()})}for(let W of h.requirements)V.push({t:H.reqLabel(W),s:`${W.level!==void 0?`L${W.level}`:"—"} ${W.kind}${W.status!==""?` · ${W.status}`:""} · ${H.reqPath(W)}`,h:H.reqPage(W),k:`${H.reqPath(W)} ${W.node.id} ${H.reqLabel(W)} ${W.req.statement}`.toLowerCase()});return{nodes:Z,edges:h.modelEdges().filter((W)=>z.has(W.from)&&z.has(W.to)).map((W)=>({s:W.from,t:W.to,k:W.kind,...W.via!==void 0?{v:fq(W.via)}:{}})),slices:K,features:q.map((W)=>({id:W.node.id,label:H.reqLabel(W)})),reqs:b,generated:J,search:V,hasClaims:h.hasClaims(),requirementType:bh}}function fq(h){let H=h.lastIndexOf(".");return H<0?h:h.slice(H+1)}function vH(h){return BH({view:h.view,title:h.title,templates:{...V3,...h.templates},texts:h.texts,...h.footer!==""&&{stamp:h.footer},assetBase:"",cytoscapeSrc:()=>"",graph3dSrc:()=>"assets/3d-force-graph.min.js"})}globalThis.MoExplorer={explorerFor:vH,templates:V3};if(typeof document<"u")Oq(window);function Oq(h){let $,Z="",z={path:"",search:""},K=[],b=(C)=>{let Y=C.replace(/^#\/?/,""),j=new URL(Y===""?"index.html":Y,"http://explorer.invalid/"),Q=j.pathname.slice(1);try{Q=decodeURIComponent(Q)}catch{}return{path:Q===""?"index.html":Q,search:j.search,anchor:j.hash.slice(1)}},J=(C,Y,j="")=>`#/${C}${Y}${j!==""?`#${j}`:""}`;h.MO_APP={href:(C)=>{let Y=b(C);return J(Y.path,Y.search,Y.anchor)},search:()=>z.search,replaceQuery:(C)=>{z={path:z.path,search:C==="?"?"":C},history.replaceState(null,"",J(z.path,z.search))},listen:(C,Y)=>{document.addEventListener(C,Y),K.push(()=>document.removeEventListener(C,Y))},onLeave:(C)=>{K.push(C)}};let V=(C=h.MO_MODEL)=>{if(C===void 0)return!1;return $=vH(C),h.MO_EXPLORER=$.graphData(),Z=C.stamp,!0},y=new URLSearchParams(location.search).get("source"),w,v;if(y!==null&&y!=="")try{w=new URL(y,location.href)}catch{}let l=()=>{if(y===null||y==="")return;let C=v?.ok??!1,Y=r3(w?.href??y),j=C?`● Following the running application at ${Y}`:`● Cannot read ${Y}${v!==void 0&&v.error!==""?` (${r3(v.error)})`:""}${$!==void 0?", showing the model it last served":""}; trying again every second`,Q=document.getElementById("mo-live");if(Q===null)Q=document.createElement("div"),Q.id="mo-live",document.body.appendChild(Q);if(Q.innerHTML!==j)Q.innerHTML=j;let m=C?"live-source":"live-source down";if(Q.className!==m)Q.className=m;if(v!==void 0)Q.dataset.checked=new Date(v.at).toISOString();document.documentElement.setAttribute("data-mo-source",C?"live":"down")},k=(C,Y,j)=>{for(let Q of Array.from(C.querySelectorAll("a[href]"))){let m=Q.getAttribute("href");if(/^[a-z][a-z0-9+.-]*:/i.test(m))continue;if(m.startsWith("#")){Q.setAttribute("href",J(Y,j,m.slice(1)));continue}let G=new URL(m,"http://explorer.invalid/"+Y);Q.setAttribute("href",J(G.pathname.slice(1),G.search,G.hash.slice(1)))}},D=(C)=>{let Y=b(location.hash),j=$?.pages.get(Y.path);for(let u of K)u();K=[],z={path:Y.path,search:Y.search};let Q=j!==void 0?j():`Not found

    No such page

    ${r3(Y.path)} is not a page of this model.

    Overview

    `,m=new DOMParser().parseFromString(Q,"text/html");m.querySelectorAll("script").forEach((u)=>u.remove()),k(m,Y.path,Y.search);let G=window.scrollY;document.title=m.title;for(let u of Array.from(document.body.attributes))document.body.removeAttribute(u.name);for(let u of Array.from(m.body.attributes))document.body.setAttribute(u.name,u.value);if(document.body.replaceChildren(...Array.from(m.body.childNodes).map((u)=>document.importNode(u,!0))),j!==void 0)h.MO_THEME?.();if(C)window.scrollTo(0,G);else if(Y.anchor!=="")document.getElementById(Y.anchor)?.scrollIntoView();else window.scrollTo(0,0);document.documentElement.setAttribute("data-mo-route",Y.path),l()};window.addEventListener("hashchange",()=>{let C=b(location.hash);if(C.path===z.path&&C.search===z.search){if(C.anchor!=="")document.getElementById(C.anchor)?.scrollIntoView();return}D(!1)});let g=(C,Y)=>{let j=document.createElement("script");j.src=`${C}?t=${Date.now()}`,j.onload=()=>{j.remove(),Y()},j.onerror=()=>{j.remove(),Y()},document.head.appendChild(j)},F=()=>{g("explorer-stamp.js",()=>{if(h.MO_STAMP===void 0||h.MO_STAMP===Z)return void setTimeout(F,1000);let C=h.MO_STAMP;g("explorer-model.js",()=>{if(h.MO_MODEL?.stamp===C&&V())D(!0);setTimeout(F,1000)})})},d=(C)=>{let Y="",j=async()=>{try{let Q=await fetch(C.href,{cache:"no-cache"});if(!Q.ok)throw Error(`HTTP ${Q.status}`);let m=await Q.text();if(m!==Y){let G=JSON.parse(m);if(typeof G!=="object"||G===null||!String(G.format).startsWith("metaobjects-docs-view/"))throw Error("the response is not a docs view");let u=h.MO_MODEL,M=$===void 0;V({stamp:Q.headers.get("etag")??`${m.length}`,title:u?.title??C.host,footer:u?.footer??"",texts:u?.texts??{},templates:u?.templates??{},view:G}),Y=m,v={ok:!0,at:Date.now(),error:""},D(!M)}else v={ok:!0,at:Date.now(),error:""},l()}catch(Q){if(v={ok:!1,at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},$===void 0)document.body.innerHTML="

    No model yet

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

    ";l()}setTimeout(()=>void j(),1000)};j()},B=()=>{if(y!==null&&y!==""){if(w===void 0){v={ok:!1,at:Date.now(),error:"not a URL"},document.body.innerHTML="

    No model

    The source parameter is not a URL.

    ",l();return}d(w);return}if(!V())document.body.innerHTML="

    No model

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

    ";else D(!1);setTimeout(F,1000)};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",B);else B()}function r3(h){return h.replace(/[&<>"']/g,(H)=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[H])}})(); + */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/typescript/packages/docs-site/scripts/build-app.ts b/server/typescript/packages/docs-site/scripts/build-app.ts index 3460281960..c271aa3291 100644 --- a/server/typescript/packages/docs-site/scripts/build-app.ts +++ b/server/typescript/packages/docs-site/scripts/build-app.ts @@ -8,8 +8,9 @@ // theme beside it. Cytoscape (`assets/cytoscape.min.js`) is vendored in `explorer-app/` and is // not touched here. Run `scripts/sync-explorer-app.sh` afterwards to refresh every port's copy. // -// The committed bundle is minified, and minified output follows the Bun version, so it is built -// and checked with one Bun only: the version the workflows pin (`bun-version` in +// The committed bundle is minified (whitespace and syntax only; identifiers keep their names, so +// the bytes do not depend on the minifier's naming), and minified output follows the Bun version, +// so it is built and checked with one Bun only: the version the workflows pin (`bun-version` in // `.github/workflows/`). Any other Bun refuses rather than reporting a stale bundle. import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; @@ -50,7 +51,9 @@ export async function buildExplorerApp(): Promise> { entrypoints: [join(PKG, "app-src/main.ts")], target: "browser", format: "iife", - minify: true, + // Identifier renaming is off: Bun's choice of short names is not stable from one build to + // the next, so a renamed bundle would fail the committed-bytes check on unchanged sources. + minify: { whitespace: true, syntax: true, identifiers: false }, banner: MUSTACHE_NOTICE, // Bundle the workspace packages from their sources (the `bun` export condition), never from // a `dist/` that may be stale or missing. From 2fbd5eb796f9227cfbe12a87feda127cd7f8f264 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 02:36:20 -0500 Subject: [PATCH 05/13] feat(java): build the docs view and write the model explorer on the JVM, with no Node The JVM builds the port-neutral docs view from its loaded model (DocsView), byte for byte what TypeScript builds for every fixtures/explorer-conformance case, gated in the metadata suite. A docs-site generator (DocsSiteGenerator, registered in the Java and Kotlin registries, eject-exempt like TypeScript's) writes explorer.json, the shared explorer app, explorer-model.js and explorer-stamp.js, and lists each node's generated files from the hash manifest's provenance. Kotlin runs the same class, and its suite gates every corpus case through its own registry. MetaEndpoint gains the /_meta/docs helpers (body, ETag, If-None-Match), mounted by the host as /_meta is. Needs the HashManifest.loadProvenance API from #669. --- changelog.d/explorer-jvm.md | 10 + docs/CONFORMANCE.md | 5 +- docs/features/explorer-site.md | 47 +- docs/features/metadata-api.md | 39 +- docs/ports/java.md | 1 + docs/ports/kotlin.md | 5 +- fixtures/explorer-conformance/README.md | 9 + .../registry.json | 4 +- .../docs/explorer/ExplorerSite.java | 226 ++++ .../generator/DocsSiteGenerator.java | 152 +++ .../docs/explorer/ExplorerSiteTest.java | 195 ++++ .../generator/kotlin/GeneratorRegistry.kt | 12 + .../kotlin/KotlinDocsSiteConformanceTest.kt | 48 + .../generator/GeneratorRegistry.java | 7 + .../mojo/AbstractMetaDataMojo.java | 4 + .../com/metaobjects/mojo/EjectSupport.java | 3 +- .../metadata/ktx/MetaEndpointKtxTest.kt | 9 + .../com/metaobjects/docsview/DocsView.java | 1006 +++++++++++++++++ .../metaobjects/docsview/DocsViewJson.java | 173 +++ .../io/json/CanonicalJsonSerializer.java | 6 +- .../com/metaobjects/io/json/MetaEndpoint.java | 94 ++ .../docsview/DocsViewConformanceTest.java | 157 +++ .../io/json/MetaDocsEndpointTest.java | 76 ++ 23 files changed, 2270 insertions(+), 18 deletions(-) create mode 100644 changelog.d/explorer-jvm.md create mode 100644 server/java/codegen-base/src/main/java/com/metaobjects/docs/explorer/ExplorerSite.java create mode 100644 server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java create mode 100644 server/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java create mode 100644 server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDocsSiteConformanceTest.kt create mode 100644 server/java/metadata/src/main/java/com/metaobjects/docsview/DocsView.java create mode 100644 server/java/metadata/src/main/java/com/metaobjects/docsview/DocsViewJson.java create mode 100644 server/java/metadata/src/test/java/com/metaobjects/docsview/DocsViewConformanceTest.java create mode 100644 server/java/metadata/src/test/java/com/metaobjects/io/json/MetaDocsEndpointTest.java diff --git a/changelog.d/explorer-jvm.md b/changelog.d/explorer-jvm.md new file mode 100644 index 0000000000..d879739e07 --- /dev/null +++ b/changelog.d/explorer-jvm.md @@ -0,0 +1,10 @@ +- **Java and Kotlin: the model explorer with no Node.** The JVM builds the docs view from its + loaded model (`com.metaobjects.docsview.DocsView`), byte for byte what TypeScript builds for + every `fixtures/explorer-conformance/` case. A new `docs-site` generator + (`com.metaobjects.generator.DocsSiteGenerator`, in both the Java and Kotlin registries) writes + `explorer.json`, the explorer app, `explorer-model.js` and `explorer-stamp.js`; each object + lists the generated files the committed hash manifest records for it. Optional args name a + `verify --format json` payload (`verifyFile`) and the routes (`routesFile`). The running + application can serve the same view at `{apiPrefix}/_meta/docs`: `MetaEndpoint.docs(root)` + builds it once and carries its ETag, and the host mounts it as it mounts `/_meta`. The static + export and the classic site stay TypeScript's. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 86264bbe6c..5bb859c3d4 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`) | ✓ | — | — | — | — | — | +| [`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`) | — | — | — | **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 @@ -912,6 +912,9 @@ It also pins three id rules: a page declared before the entity it shares a name entity its claims, a reference and a claim naming an inherited member land on the owner's row, and a nameless member keeps its index in its label. `model-alone` carries no optional input: its `expected.json` is the body the running application's `GET {apiPrefix}/_meta/docs` serves. +Java (`metadata`'s `DocsViewConformanceTest`, and `codegen-base`'s `ExplorerSiteTest` through the +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. **One port runs it:** TypeScript, in `server/typescript/packages/metadata/test/docs-view-conformance.test.ts` (the view) and diff --git a/docs/features/explorer-site.md b/docs/features/explorer-site.md index 9bdae2d391..a59b65feaf 100644 --- a/docs/features/explorer-site.md +++ b/docs/features/explorer-site.md @@ -62,6 +62,37 @@ opening a link in a new tab work as they do on a static site. The app files are every port; `explorer-app/README.md` at the repository root describes them and the two data files a port writes beside them. +### In each port + +The explorer app is the same files in every port, and `explorer.json` is the same bytes for the +same model and inputs: every port that builds the docs view is held to +`fixtures/explorer-conformance/`. What differs is where each input comes from. + +| Port | Generator | The app | Inputs it reads | +|---|---|---|---| +| 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 the committed hash manifest records per node, 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 | +| C#, Python, Rust | not yet | | | + +On the JVM, wire it like any other generator, with its own output directory: + +```xml + + com.metaobjects.generator.DocsSiteGenerator + + ${project.basedir}/docs/generated + + +``` + +It writes `docs/generated/site/`. The JVM build has no requirement gate of its own, so without +`verifyFile` the requirement tree shows each claim but no verdict. The generator is not told the +routes the Spring controllers mount, so no node lists its REST routes. The generated-file lists come +from the hash manifest, which a write run saves after every generator has run: they show the +files the previous write run recorded. The other args are in +[the Java port's generator table](../ports/java.md#generators). + ### The live view Leave the explorer open while you work. About once a second it reloads `explorer-stamp.js`, @@ -264,18 +295,24 @@ 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 the other ports: the contract is in +- The docs view route in C#, Python and Rust: 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. -- The app in the other ports: 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)`). +- The app in C#, Python and Rust: 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 JVM, Python and C# generators (see - [explorer-data.md](explorer-data.md)), so for those ports the generated-file lists are empty. ## Verified by +- `server/java/metadata/src/test/java/com/metaobjects/docsview/DocsViewConformanceTest.java`: + the JVM docs view builder writes every `fixtures/explorer-conformance/` case byte for byte. +- `server/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java`: + the JVM site's app files are the canonical copy, its model script has TypeScript's bytes 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/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 ebcf95aa4d..fd4d35ca69 100644 --- a/docs/features/metadata-api.md +++ b/docs/features/metadata-api.md @@ -224,9 +224,42 @@ app.use(`/api${META_DOCS_ROUTE_PATH}`, requireAuth); mountMetaDocsRouteHono({ app, root, prefix: "/api" }); ``` -C#, Java, Kotlin, Python and Rust 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. +Java and Kotlin ship the helper and leave the mount to the host, as for `/_meta`: +`MetaEndpoint.META_DOCS_ROUTE_PATH`, `MetaEndpoint.metaDocsJson(root)` and +`MetaEndpoint.docs(root)`, which builds the view once and carries its ETag +(`metaDocsEtag`, the value TypeScript's mounts send) and the `If-None-Match` check. + +```java +// MetaDocsController.java +import com.metaobjects.io.json.MetaEndpoint; +import org.springframework.http.CacheControl; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class MetaDocsController { + // root: the MetaRoot this app loaded. Built once: the model does not change after load. + private final MetaEndpoint.Docs docs = MetaEndpoint.docs(root); + + @GetMapping("/api" + MetaEndpoint.META_DOCS_ROUTE_PATH) + public ResponseEntity docs(@RequestHeader(value = "If-None-Match", required = false) String tag) { + ResponseEntity.BodyBuilder res = (docs.matches(tag) ? ResponseEntity.status(HttpStatus.NOT_MODIFIED) : ResponseEntity.ok()) + .eTag(docs.etag()).cacheControl(CacheControl.noCache()); + return docs.matches(tag) ? res.build() : res.contentType(MediaType.APPLICATION_JSON).body(docs.body()); + } +} +``` + +Kotlin calls the same symbols through `metadata-ktx`. To let the explorer read the route from +`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 +body that builder writes; their `/_meta` sections above show where each mounts it. ## Browser consumption diff --git a/docs/ports/java.md b/docs/ports/java.md index f8d7638489..e247378a95 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -469,6 +469,7 @@ name in every port. | `api-docs` | `JavaApiDocsGenerator` | `metaobjects-codegen-spring` | The Java SDK api reference: one page per entity, value object, projection, served report and template, an index and `AGENT-API.md`, under `/`. A `` entry like any other, run by `metaobjects:generate` and checked by `metaobjects:verify`. Args: `outputDir` (required; give it generated files only, since `verify` compares the whole tree), `apiSubDir` (default `api/java`), `layout` (`flat`, the default, or `package`), `projectName` (the agent page's header label, default `project`) and `modelBaseUrl` (absolute base for the links to the model pages; with none set the pages carry no `Model / metadata` link, since nothing writes a page for it to point at). The `metaobjects:docs` goal was removed in 8.1.0 ([migration](../features/migrations/docs-are-generators.md#java-and-kotlin)). Ejectable: the copy takes the page IR, the builder, the renderer, the page paths and the page templates with it. | | `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. | +| `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 generated files the committed hash manifest records for it (`generatedBy`, `sourceNode`), as of the last write run. 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) and `genStateDir` (default `.metaobjects/.gen-state`). 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. | | `json-schema` | `MetaDataFileJsonSchemaGenerator` | `metaobjects-codegen-base` | A JSON Schema that validates metadata files, built from the type registry (`outputDir`, `outputFilename`). Ejectable: the copy takes `MetaDataFileSchemaWriter` with it. | diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index e05ee86362..b718a132de 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 18 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): +The 20 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): | Generator | Output | Per | |---|---|---| @@ -187,6 +187,7 @@ The 18 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): | `KotlinSharedModelGenerator` | `.metaobjects.json` and `metaobjects.pkg.json` — the FR-023 shared-model artifact and manifest a consumer's `meta deps sync` reads. See [Publishing a shared model](#publishing-a-shared-model-shared-model) | once per project (`include` selects the nodes) | | `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 | +| `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 the committed hash manifest. 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 project. Keep `` at plugin level and bind the goal in ``: without the @@ -318,7 +319,7 @@ copies `KotlinSharedModelGenerator.kt` into a `codegen/` module under your packa ### Declarative template-codegen (`TemplateScopeGenerator`) -The 18 generators above are not the ceiling. When you need a shape +The 20 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/fixtures/explorer-conformance/README.md b/fixtures/explorer-conformance/README.md index ffe570c98e..150e0578f4 100644 --- a/fixtures/explorer-conformance/README.md +++ b/fixtures/explorer-conformance/README.md @@ -101,3 +101,12 @@ Then review the diff: every changed line is a change to what a docs page can sho committed `verify.json`, and a fresh shop payload still builds `shop/expected.json`. - `server/typescript/packages/runtime-ts/test/meta-docs-route.test.ts`: the docs view route serves `model-alone/expected.json` for that case's model. +- `server/java/metadata/src/test/java/com/metaobjects/docsview/DocsViewConformanceTest.java`: + the JVM builder reproduces every case. It applies `provider.json` as a test provider, every + type a plain node. +- `server/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java` + and `server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDocsSiteConformanceTest.kt`: + the Java and Kotlin `docs-site` generators write every case's `explorer.json`, reading + `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`. diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index a6a3d2e7f1..a6d513edba 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": "TYPESCRIPT ONLY: it was `meta docs --site` until 1.1.0 (ADR-0034 Amendment 9).", + "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.", "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"] + "ports": ["typescript", "java", "kotlin"] }, "plantuml": { "concept": "PlantUML class diagram of the object model.", diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/docs/explorer/ExplorerSite.java b/server/java/codegen-base/src/main/java/com/metaobjects/docs/explorer/ExplorerSite.java new file mode 100644 index 0000000000..309dff21de --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/docs/explorer/ExplorerSite.java @@ -0,0 +1,226 @@ +package com.metaobjects.docs.explorer; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.metaobjects.docsview.DocsView; +import com.metaobjects.docsview.DocsViewJson; +import com.metaobjects.template.TemplateConstants; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * The model explorer as one browser app over the docs view, written with no Node on the path: the + * JVM side of TypeScript's {@code generateExplorerSite} ({@code output: "app"}). The Java and Kotlin + * {@code docs-site} generators both write through here. + * + *

    What it writes, relative to the site directory:

    + *
    + *   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                 jar 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 page-per-screen static export ({@code output: "static"}) draws its pages with the + * TypeScript page code and stays in TypeScript.

    + */ +public final class ExplorerSite { + + private ExplorerSite() {} + + /** The data files the app reads, beside its shell. */ + public static final String MODEL_FILE = "explorer-model.js"; + public static final String STAMP_FILE = "explorer-stamp.js"; + public static final String VIEW_FILE = "explorer.json"; + + /** The app's files: every port ships the same bytes (TypeScript's {@code EXPLORER_APP_FILES}). */ + public static final List APP_FILES = List.of( + "index.html", + "assets/explorer-app.js", + "assets/explorer.css", + "assets/explorer.js", + "assets/cytoscape.min.js", + "assets/3d-force-graph.min.js"); + + /** The theme pair a project may own ({@code assets/} under the owned docs-site directory). */ + public static final List THEME_ASSETS = List.of("explorer.css", "explorer.js"); + + /** The templates an owned theme may replace; the app uses an owned one in place of its own. */ + public static final List TEMPLATE_NAMES = List.of( + "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"); + + /** Where this jar carries its copy of {@code explorer-app/}. */ + static final String APP_RESOURCE_ROOT = "metaobjects/explorer-app/"; + + /** + * What the site is built from. + * + * @param view the docs view ({@link DocsView#build}) + * @param title the project's name, as the header and the home page print it + * @param footer printed in every footer; {@code ""} for none + * @param texts prompt text by template node id + * @param assetsDir an owned theme directory (holding {@code explorer.css}, {@code explorer.js}), or null + * @param templatesDir an owned templates directory, or null + */ + public record Input(JsonObject view, String title, String footer, Map texts, + Path assetsDir, Path templatesDir) {} + + /** Every file of the site, site-relative, in write order. */ + public static Map emit(Input in) { + Map files = new LinkedHashMap<>(); + for (String f : APP_FILES) { + String asset = f.startsWith("assets/") ? f.substring("assets/".length()) : null; + if (asset != null && THEME_ASSETS.contains(asset)) continue; + files.put(f, resource(f)); + } + for (String a : THEME_ASSETS) { + String owned = readIfPresent(in.assetsDir(), a); + files.put("assets/" + a, owned != null ? owned : resource("assets/" + a)); + } + Map templates = new TreeMap<>(); + for (String name : TEMPLATE_NAMES) { + String owned = readIfPresent(in.templatesDir(), name); + if (owned != null) templates.put(name, owned); + } + ModelScript model = modelScript(in.title(), in.footer(), in.texts(), templates, in.view()); + files.put(MODEL_FILE, model.script()); + files.put(STAMP_FILE, stampScript(model.stamp())); + files.put(VIEW_FILE, DocsView.serialize(in.view())); + return files; + } + + /** The app's data script and the stamp it carries. */ + public record ModelScript(String script, String stamp) {} + + /** + * The app's data file: one script setting {@code window.MO_MODEL}. Its {@code stamp} is the + * first 16 hex digits of the SHA-256 of the model's compact JSON without the stamp, and the + * stamp file repeats it. The same shape and bytes as TypeScript's {@code explorerModelScript}. + */ + public static ModelScript modelScript(String title, String footer, Map texts, + Map templates, JsonObject view) { + JsonObject rest = new JsonObject(); + rest.addProperty("title", title); + rest.addProperty("footer", footer == null ? "" : footer); + rest.add("texts", sortedStrings(texts)); + rest.add("templates", sortedStrings(templates)); + rest.add("view", view); + String json = DocsViewJson.compact(rest); + String stamp = sha256(json).substring(0, 16); + return new ModelScript("window.MO_MODEL = {\"stamp\":" + DocsViewJson.quote(stamp) + "," + json.substring(1) + ";\n", stamp); + } + + /** The file the app polls. */ + public static String stampScript(String stamp) { + return "window.MO_STAMP = " + DocsViewJson.quote(stamp) + ";\n"; + } + + /** + * Each prompt's {@code .mustache} text from the directories its {@code @textRef} resolves in, + * by template node id. A ref that is absolute or climbs out with {@code ..} is not read, so a + * model cannot pull an arbitrary file into a published page. + */ + public static Map readPromptTexts(JsonObject view, List dirs) { + Map out = new TreeMap<>(); + for (JsonElement el : view.getAsJsonArray("nodes")) { + JsonObject n = el.getAsJsonObject(); + String ref = null; + for (JsonElement a : n.getAsJsonArray("attrs")) { + JsonObject attr = a.getAsJsonObject(); + if (TemplateConstants.ATTR_TEXT_REF.equals(attr.get("name").getAsString()) + && attr.get("value").isJsonPrimitive() && attr.get("value").getAsJsonPrimitive().isString()) { + ref = attr.get("value").getAsString(); + } + } + if (ref == null) continue; + String[] segments = ref.split("[\\\\/]", -1); + boolean unsafe = Path.of(ref).isAbsolute() || ref.startsWith("/") || ref.startsWith("\\"); + for (String s : segments) if (s.isEmpty() || s.equals("..")) unsafe = true; + if (unsafe) continue; + for (Path d : dirs) { + Path p = d; + for (int i = 0; i < segments.length; i++) { + p = p.resolve(i == segments.length - 1 ? segments[i] + ".mustache" : segments[i]); + } + if (Files.isRegularFile(p)) { + out.put(n.get("id").getAsString(), read(p)); + break; + } + } + } + return out; + } + + private static JsonObject sortedStrings(Map m) { + JsonObject o = new JsonObject(); + for (Map.Entry e : new TreeMap<>(m == null ? Map.of() : m).entrySet()) { + o.addProperty(e.getKey(), e.getValue()); + } + return o; + } + + private static String sha256(String s) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private static String readIfPresent(Path dir, String name) { + if (dir == null) return null; + Path p = dir.resolve(name); + return Files.isRegularFile(p) ? read(p) : null; + } + + private static String read(Path p) { + try { + return Files.readString(p, StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException("docs-site: could not read " + p, e); + } + } + + /** A file of this jar's copy of the explorer app. */ + static String resource(String rel) { + String path = APP_RESOURCE_ROOT + rel; + try (InputStream in = ExplorerSite.class.getClassLoader().getResourceAsStream(path)) { + if (in == null) throw new IllegalStateException("docs-site: the explorer app file " + path + " is not on the classpath"); + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException("docs-site: could not read " + path, e); + } + } +} diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java new file mode 100644 index 0000000000..71a95b3f73 --- /dev/null +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java @@ -0,0 +1,152 @@ +package com.metaobjects.generator; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.docs.explorer.ExplorerSite; +import com.metaobjects.docsview.DocsView; +import com.metaobjects.generator.util.HashManifest; +import com.metaobjects.loader.MetaDataLoader; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * {@code docs-site}: the model explorer, one browser app over the project's docs view, written with + * no Node on the path (the JVM side of TypeScript's {@code docsSiteFile()}, {@code output: "app"}). + * The Java and Kotlin registries both run this class: the site is language-neutral, so both ports + * write the same bytes. + * + *

    It builds the docs view from the model this run loaded ({@link DocsView#build}), lists the + * generated files the committed hash manifest records for each node ({@code generatedBy} and + * {@code sourceNode}), and writes the app, its data script, its stamp and {@code explorer.json} + * through {@link ExplorerSite}. The files it lists are the ones the last write run recorded: the + * manifest is saved after every generator has run.

    + * + *

    Args: {@code outputDir} (required); {@code subDir} (default {@code site}; empty writes at the + * root); {@code title} (default: the project directory's name); {@code stamp} (footer text, default + * none, so the site depends on the model alone); {@code prompts} (a directory, relative to the + * project, holding prompt {@code .mustache} sources outside the metadata directories and + * {@code templates/}); {@code verifyFile} (a {@code verify} JSON payload whose requirement rows the + * explorer shows, default none); {@code routesFile} (the routes the application mounts, + * {@code [{ node, method, path }]} with {@code node} a resolution key, default none); {@code genStateDir} (default {@code .metaobjects/.gen-state}) and + * {@code projectRoot} (default: the working directory; the Maven plugin passes the module's).

    + * + *

    A project that owns the explorer's theme (what {@code meta eject docs-site} copies into + * {@code codegen/docs-site/}) has its {@code assets/explorer.css}, {@code assets/explorer.js} and + * {@code templates/explorer-*.mustache} used in place of the packaged ones.

    + */ +public class DocsSiteGenerator extends FileEmittingGenerator { + + private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DocsSiteGenerator.class); + + public static final String ARG_SUB_DIR = "subDir"; + public static final String ARG_TITLE = "title"; + public static final String ARG_STAMP = "stamp"; + public static final String ARG_PROMPTS = "prompts"; + public static final String ARG_VERIFY_FILE = "verifyFile"; + public static final String ARG_ROUTES_FILE = "routesFile"; + public static final String ARG_GEN_STATE_DIR = "genStateDir"; + public static final String ARG_PROJECT_ROOT = "projectRoot"; + + public static final String DEFAULT_SUB_DIR = "site"; + /** Where an owned explorer theme lives, under the project (TypeScript's {@code OWNED_DOCS_SITE_DIR}). */ + public static final String OWNED_DOCS_SITE_DIR = "codegen/docs-site"; + static final String DEFAULT_GEN_STATE_DIR = ".metaobjects/.gen-state"; + + /** + * The owned theme, the prompts directory and the verify payload are read beside the model + * (ADR-0064): editing one regenerates. The hash manifest is not an input: it changes only + * when a run writes, and that run regenerates anyway. + */ + @Override + public List extraInputs() { + Path project = Path.of(getArg(ARG_PROJECT_ROOT, System.getProperty("user.dir"))); + List inputs = new ArrayList<>(); + inputs.add(project.resolve(OWNED_DOCS_SITE_DIR).toString()); + if (hasArg(ARG_PROMPTS)) inputs.add(project.resolve(getArg(ARG_PROMPTS)).toString()); + if (hasArg(ARG_VERIFY_FILE)) inputs.add(project.resolve(getArg(ARG_VERIFY_FILE)).toString()); + if (hasArg(ARG_ROUTES_FILE)) inputs.add(project.resolve(getArg(ARG_ROUTES_FILE)).toString()); + return inputs; + } + + @Override + protected List generate(MetaDataLoader loader) { + Path project = Path.of(getArg(ARG_PROJECT_ROOT, System.getProperty("user.dir"))).toAbsolutePath().normalize(); + String dir = getArg(ARG_SUB_DIR, DEFAULT_SUB_DIR).replaceAll("/+$", ""); + String prefix = dir.isEmpty() ? "" : dir + "/"; + + JsonElement verify = hasArg(ARG_VERIFY_FILE) ? readJson(project.resolve(getArg(ARG_VERIFY_FILE))) : null; + Path genState = project.resolve(getArg(ARG_GEN_STATE_DIR, DEFAULT_GEN_STATE_DIR)); + JsonElement routes = hasArg(ARG_ROUTES_FILE) ? readJson(project.resolve(getArg(ARG_ROUTES_FILE))) : null; + JsonObject view = DocsView.build(loader.getRoot(), verify, manifest(genState), routes); + + Path owned = project.resolve(OWNED_DOCS_SITE_DIR); + Path assets = owned.resolve("assets"); + Path templates = owned.resolve("templates"); + String title = getArg(ARG_TITLE, project.getFileName() == null ? "Metadata" : project.getFileName().toString()); + Map files = ExplorerSite.emit(new ExplorerSite.Input( + view, title, getArg(ARG_STAMP, ""), + ExplorerSite.readPromptTexts(view, promptDirs(loader, project)), + Files.isDirectory(assets) ? assets : null, + Files.isDirectory(templates) ? templates : null)); + + List out = new ArrayList<>(); + for (Map.Entry f : files.entrySet()) out.add(new EmittedFile(prefix + f.getKey(), f.getValue())); + return out; + } + + /** The manifest's provenance as the docs view reads it: {@code path → { generatedBy, sourceNode }}. */ + static JsonObject manifest(Path genStateDir) { + if (!HashManifest.exists(genStateDir)) return null; + JsonObject out = new JsonObject(); + for (Map.Entry e : HashManifest.loadProvenance(genStateDir).entrySet()) { + JsonObject entry = new JsonObject(); + entry.addProperty("generatedBy", e.getValue().generatedBy()); + if (e.getValue().sourceNode() != null) entry.addProperty("sourceNode", e.getValue().sourceNode()); + out.add(e.getKey(), entry); + } + return out; + } + + /** + * Where prompt {@code .mustache} sources are looked for: the directories the model was loaded + * from, the project's {@code templates/} and the {@code prompts} directory, each once. + */ + private List promptDirs(MetaDataLoader loader, Path project) { + Set dirs = new LinkedHashSet<>(); + if (loader.getSourceURIs() != null) { + for (URI uri : loader.getSourceURIs()) { + if (!"file".equals(uri.getScheme())) continue; + Path p = Path.of(uri); + Path parent = Files.isDirectory(p) ? p : p.getParent(); + if (parent != null) dirs.add(parent.toAbsolutePath().normalize()); + } + } + Path templates = project.resolve("templates"); + if (Files.isDirectory(templates)) dirs.add(templates); + if (hasArg(ARG_PROMPTS)) { + Path prompts = project.resolve(getArg(ARG_PROMPTS)).normalize(); + if (Files.isDirectory(prompts)) dirs.add(prompts); + else log.warn("docs-site: the prompts directory does not exist: {}", prompts); + } + return new ArrayList<>(dirs); + } + + private static JsonElement readJson(Path p) { + try { + return JsonParser.parseString(Files.readString(p, StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new UncheckedIOException("docs-site: could not read " + p, e); + } + } +} 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 new file mode 100644 index 0000000000..7bf774c180 --- /dev/null +++ b/server/java/codegen-base/src/test/java/com/metaobjects/docs/explorer/ExplorerSiteTest.java @@ -0,0 +1,195 @@ +package com.metaobjects.docs.explorer; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.docsview.DocsView; +import com.metaobjects.docsview.DocsViewConformanceTest; +import com.metaobjects.generator.DocsSiteGenerator; +import com.metaobjects.loader.DirectorySource; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * The explorer site the JVM {@code docs-site} generator writes: the same files, and the same data + * script bytes, as TypeScript's {@code generateExplorerSite} ({@code output: "app"}). + */ +public class ExplorerSiteTest { + + @Rule public TemporaryFolder temp = new TemporaryFolder(); + + static Path repo() { + for (Path p = Path.of("").toAbsolutePath(); p != null; p = p.getParent()) { + if (Files.isDirectory(p.resolve("fixtures/explorer-conformance")) && Files.isDirectory(p.resolve("explorer-app"))) return p; + } + throw new IllegalStateException("repository root not found above " + Path.of("").toAbsolutePath()); + } + + static Path fixture(String name) { + return repo().resolve("fixtures/explorer-conformance").resolve(name); + } + + static JsonObject expectedView(String name) throws IOException { + return JsonParser.parseString(Files.readString(fixture(name).resolve("expected.json"))).getAsJsonObject(); + } + + static String sha256(String s) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8))); + } + + @Test + public void modelScriptIsTypeScriptsBytes() throws Exception { + Map texts = new LinkedHashMap<>(); + texts.put("b", "B\n"); + texts.put("a", "A é"); + ExplorerSite.ModelScript m = ExplorerSite.modelScript("Shop 
", "v1", texts, + 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())); + } + + @Test + public void appFilesAreTheCanonicalCopy() throws IOException { + Map files = ExplorerSite.emit(new ExplorerSite.Input(expectedView("model-alone"), "t", "", Map.of(), null, null)); + for (String f : ExplorerSite.APP_FILES) { + assertEquals(f, Files.readString(repo().resolve("explorer-app").resolve(f)), files.get(f)); + } + assertEquals(Files.readString(fixture("model-alone").resolve("expected.json")), files.get(ExplorerSite.VIEW_FILE)); + assertEquals(List.of("index.html", "assets/explorer-app.js", "assets/cytoscape.min.js", "assets/3d-force-graph.min.js", + "assets/explorer.css", "assets/explorer.js", "explorer-model.js", "explorer-stamp.js", "explorer.json"), + List.copyOf(files.keySet())); + } + + @Test + public void anOwnedThemeAndTemplateWin() throws IOException { + Path dir = temp.newFolder().toPath(); + Files.createDirectories(dir.resolve("assets")); + Files.createDirectories(dir.resolve("templates")); + Files.writeString(dir.resolve("assets/explorer.css"), "body{}"); + Files.writeString(dir.resolve("templates/explorer-head.mustache"), ""); + Files.writeString(dir.resolve("templates/not-a-template.mustache"), "ignored"); + Map files = ExplorerSite.emit(new ExplorerSite.Input(expectedView("model-alone"), "t", "", Map.of(), + dir.resolve("assets"), dir.resolve("templates"))); + assertEquals("body{}", files.get("assets/explorer.css")); + assertEquals(Files.readString(repo().resolve("explorer-app/assets/explorer.js")), files.get("assets/explorer.js")); + String model = files.get(ExplorerSite.MODEL_FILE); + assertTrue("owned template carried", model.contains("\"templates\":{\"explorer-head.mustache\":\"\"}")); + } + + @Test + public void promptTextsReadBelowTheDirectoriesOnly() throws IOException { + Path dir = temp.newFolder().toPath(); + JsonObject view = expectedView("shop"); + Map texts = ExplorerSite.readPromptTexts(view, List.of(dir, fixture("shop").resolve("project/prompts"))); + assertEquals(1, texts.size()); + assertEquals(Files.readString(fixture("shop").resolve("project/prompts/shop/order-note.mustache")), + texts.values().iterator().next()); + + JsonObject climbing = JsonParser.parseString(view.toString().replace("\"shop/order-note\"", "\"../order-note\"")).getAsJsonObject(); + assertEquals(Map.of(), ExplorerSite.readPromptTexts(climbing, List.of(fixture("shop").resolve("project/prompts/shop")))); + } + + @Test + public void generatorWritesTheSiteFromTheLoadedModel() throws IOException { + Path out = temp.newFolder().toPath(); + Path project = fixture("model-alone").resolve("project"); + MetaDataLoader loader = new MetaDataLoader(LoaderOptions.create(false, false, true), + MetaDataLoader.SUBTYPE_MANUAL, "docs_site_generator"); + loader.init(); + loader.load(new DirectorySource(project.resolve("metaobjects"), new DirectorySource.Options()).expandToList()); + assertTrue("clean load expected: " + loader.getErrors(), loader.getErrors().isEmpty()); + + DocsSiteGenerator g = new DocsSiteGenerator(); + g.setArgs(Map.of("outputDir", out.toString(), DocsSiteGenerator.ARG_PROJECT_ROOT, project.toString())); + g.execute(loader); + + assertEquals(Files.readString(fixture("model-alone").resolve("expected.json")), + Files.readString(out.resolve("site/explorer.json"))); + assertEquals(DocsView.serialize(DocsView.build(loader.getRoot())), Files.readString(out.resolve("site/explorer.json"))); + String model = Files.readString(out.resolve("site/explorer-model.js")); + assertTrue(model.substring(0, 40), model.startsWith("window.MO_MODEL = {\"stamp\":")); + assertTrue("title defaults to the project directory's name", model.contains("\"title\":\"project\"")); + for (String f : ExplorerSite.APP_FILES) assertTrue(f, Files.isRegularFile(out.resolve("site").resolve(f))); + } + + @Test + public void generatorListsTheFilesTheManifestRecords() throws IOException { + Path tmp = temp.newFolder().toPath(); + Path project = fixture("shop").resolve("project"); + MetaDataLoader loader = new MetaDataLoader(LoaderOptions.create(false, false, true), + MetaDataLoader.SUBTYPE_MANUAL, "docs_site_generator_shop"); + loader.init(); + loader.load(new DirectorySource(project.resolve("metaobjects"), new DirectorySource.Options()).expandToList()); + assertTrue("clean load expected: " + loader.getErrors(), loader.getErrors().isEmpty()); + + // The fixture's hashes.json is the single-file manifest form HashManifest still reads. + Path genState = tmp.resolve("gen-state"); + Files.createDirectories(genState); + Files.copy(fixture("shop").resolve("hashes.json"), genState.resolve(".hashes.json")); + + DocsSiteGenerator g = new DocsSiteGenerator(); + g.setArgs(Map.of("outputDir", tmp.resolve("out").toString(), DocsSiteGenerator.ARG_PROJECT_ROOT, project.toString(), + DocsSiteGenerator.ARG_GEN_STATE_DIR, genState.toString(), DocsSiteGenerator.ARG_SUB_DIR, "", + DocsSiteGenerator.ARG_PROMPTS, "prompts", + DocsSiteGenerator.ARG_VERIFY_FILE, fixture("shop").resolve("verify.json").toString())); + g.execute(loader); + + JsonObject built = DocsView.build(loader.getRoot(), + JsonParser.parseString(Files.readString(fixture("shop").resolve("verify.json"))), + JsonParser.parseString(Files.readString(fixture("shop").resolve("hashes.json"))), null); + assertEquals(DocsView.serialize(built), Files.readString(tmp.resolve("out/explorer.json"))); + assertTrue(Files.readString(tmp.resolve("out/explorer.json")).contains("\"generatedBy\": \"queries\"")); + assertTrue("prompt text carried", Files.readString(tmp.resolve("out/explorer-model.js")).contains("\"texts\":{\"")); + } + + /** + * The generator's args for one corpus case: its project, its verify payload and routes when + * present, and its hashes.json as the gen-state manifest (the single-file form HashManifest + * still reads). The Kotlin suite runs the same case set through its registry. + */ + public static Map corpusArgs(String name, Path tmp) throws IOException { + Path dir = DocsViewConformanceTest.corpus().resolve(name); + Path genState = tmp.resolve("gen-state"); + Files.createDirectories(genState); + if (Files.isRegularFile(dir.resolve("hashes.json"))) Files.copy(dir.resolve("hashes.json"), genState.resolve(".hashes.json")); + Map args = new HashMap<>(); + args.put("outputDir", tmp.resolve("out").toString()); + args.put(DocsSiteGenerator.ARG_PROJECT_ROOT, dir.resolve("project").toString()); + args.put(DocsSiteGenerator.ARG_GEN_STATE_DIR, genState.toString()); + if (Files.isRegularFile(dir.resolve("verify.json"))) args.put(DocsSiteGenerator.ARG_VERIFY_FILE, dir.resolve("verify.json").toString()); + if (Files.isRegularFile(dir.resolve("routes.json"))) args.put(DocsSiteGenerator.ARG_ROUTES_FILE, dir.resolve("routes.json").toString()); + return args; + } + + @Test + public void generatorWritesEveryCorpusCaseByteForByte() throws IOException { + for (String name : DocsViewConformanceTest.fixtures()) { + Path tmp = temp.newFolder(name).toPath(); + DocsSiteGenerator g = new DocsSiteGenerator(); + g.setArgs(corpusArgs(name, tmp)); + g.execute(DocsViewConformanceTest.load(name)); + assertEquals(name, Files.readString(DocsViewConformanceTest.corpus().resolve(name).resolve("expected.json")), + Files.readString(tmp.resolve("out/site/explorer.json"))); + } + } +} 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 65dd610449..a217768522 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 @@ -19,6 +19,7 @@ package com.metaobjects.generator.kotlin +import com.metaobjects.generator.DocsSiteGenerator import com.metaobjects.generator.Generator import com.metaobjects.generator.direct.MultiFileDirectGeneratorBase import com.metaobjects.generator.kotlin.apidocs.DocsPaths @@ -312,6 +313,17 @@ val GENERATOR_REGISTRY: Map = linkedMapOf( factory = ::KotlinMetamodelDocsGenerator, ejectResourcePath = ejectPath("KotlinMetamodelDocsGenerator"), ), + // 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( + name = "docs-site", + description = "The model explorer: one browser app over the project's docs view (explorer.json), with " + + "the requirement tree, the model map, a page per object, prompt and requirement, the coverage matrix " + + "and the generated files the hash manifest records. Needs no Node.", + tier = GeneratorTier.NEUTRAL, + layer = GeneratorLayer.DOCS, + factory = ::DocsSiteGenerator, + ), "report-export" to GeneratorInfo( name = "report-export", description = "Per-served-report export module (Export: columns, wire-form cells, CSV and XML " + diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDocsSiteConformanceTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDocsSiteConformanceTest.kt new file mode 100644 index 0000000000..fde3fd1c05 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDocsSiteConformanceTest.kt @@ -0,0 +1,48 @@ +package com.metaobjects.generator.kotlin + +import com.metaobjects.docsview.DocsViewConformanceTest +import com.metaobjects.generator.DocsSiteGenerator +import com.metaobjects.generator.GeneratorBase +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The Kotlin port's `docs-site`, run through this port's registry, writes every + * `fixtures/explorer-conformance/` case's `explorer.json` byte for byte, as TypeScript and Java do. + */ +class KotlinDocsSiteConformanceTest { + + @Test + fun `docs-site writes every explorer-conformance case byte for byte`(@TempDir tmp: Path) { + val info = getGenerator("docs-site") ?: error("docs-site is not in the Kotlin registry") + assertEquals(null, info.ejectResourcePath, "docs-site is eject-exempt") + for (name in DocsViewConformanceTest.fixtures()) { + val dir = DocsViewConformanceTest.corpus().resolve(name) + val work = tmp.resolve(name) + val genState = Files.createDirectories(work.resolve("gen-state")) + if (Files.isRegularFile(dir.resolve("hashes.json"))) Files.copy(dir.resolve("hashes.json"), genState.resolve(".hashes.json")) + val args = mutableMapOf( + GeneratorBase.ARG_OUTPUTDIR to work.resolve("out").toString(), + DocsSiteGenerator.ARG_PROJECT_ROOT to dir.resolve("project").toString(), + DocsSiteGenerator.ARG_GEN_STATE_DIR to genState.toString(), + ) + if (Files.isRegularFile(dir.resolve("verify.json"))) args[DocsSiteGenerator.ARG_VERIFY_FILE] = dir.resolve("verify.json").toString() + if (Files.isRegularFile(dir.resolve("routes.json"))) args[DocsSiteGenerator.ARG_ROUTES_FILE] = dir.resolve("routes.json").toString() + val generator = info.factory() + generator.setArgs(args) + generator.execute(DocsViewConformanceTest.load(name)) + assertEquals( + Files.readString(dir.resolve("expected.json")), + Files.readString(work.resolve("out/site/explorer.json")), + name, + ) + for (f in listOf("index.html", "assets/explorer-app.js", "explorer-model.js", "explorer-stamp.js")) { + assertTrue(Files.isRegularFile(work.resolve("out/site").resolve(f)), "$name: $f") + } + } + } +} 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 1af6d719c5..8fd278bd95 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 @@ -497,6 +497,13 @@ 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)); + // 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(), + "The model explorer: one browser app over the project's docs view (explorer.json), with " + + "the requirement tree, the model map, a page per object, prompt and requirement, the " + + "coverage matrix and the generated files the hash manifest records. Needs no Node.", + Tier.NEUTRAL, Layer.DOCS); register(m, "plantuml", PLANTUML_GENERATOR, "PlantUML class diagram of the object model.", Tier.NATIVE, Layer.DOCS, EJECT_RESOURCE_ROOT + "PlantUMLGenerator.java", List.of(), null, List.of(PLANTUML_WRITER)); diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java index a7016f6fae..60cef1daab 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java @@ -5,6 +5,7 @@ import com.metaobjects.ErrorCode; import com.metaobjects.MetaDataException; import com.metaobjects.agentcontext.AgentContextScaffold; +import com.metaobjects.generator.DocsSiteGenerator; import com.metaobjects.generator.Generator; import com.metaobjects.generator.GeneratorBase; import com.metaobjects.generator.ProjectClassLoaderAware; @@ -946,6 +947,9 @@ public Map mergeAndOverwriteArgs(GeneratorParam g) { Map allargs = mergeArgs(globals, g.getArgs()); // Maven's project version, as a default a generator's own `version` arg overrides. if ( project != null && project.getVersion() != null ) allargs.putIfAbsent(SharedModelGenerator.ARG_VERSION, project.getVersion()); + // The module directory, as a default: docs-site resolves its project-relative inputs (the + // hash manifest, the owned theme, prompts, the verify payload) against it. + if ( project != null && project.getBasedir() != null ) allargs.putIfAbsent(DocsSiteGenerator.ARG_PROJECT_ROOT, project.getBasedir().getAbsolutePath()); // Dump the args to debug getLog().debug( "-- Generator ["+g.getClass().getSimpleName()+"] merged Args"); diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/EjectSupport.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/EjectSupport.java index 1caecc77a1..d6c80407ee 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/EjectSupport.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/EjectSupport.java @@ -193,8 +193,7 @@ public static List allEntries() { // registry's factory closure constructs them, so the FQN is the class it builds // (calling it must not throw — the registry's own contract). The ejectable resource // is named after the class's simple name, e.g. "KotlinNamesGenerator.kt". - String classname = info.getEjectResourcePath() == null ? null - : info.getFactory().invoke().getClass().getName(); + String classname = info.getFactory().invoke().getClass().getName(); out.add(new Entry(Port.KOTLIN, info.getName(), classname, info.getDescription(), info.getEjectResourcePath(), List.of(), null, info.getEjectWith())); } diff --git a/server/java/metadata-ktx/src/test/kotlin/com/metaobjects/metadata/ktx/MetaEndpointKtxTest.kt b/server/java/metadata-ktx/src/test/kotlin/com/metaobjects/metadata/ktx/MetaEndpointKtxTest.kt index 9d0fd2fb75..cc40645aa4 100644 --- a/server/java/metadata-ktx/src/test/kotlin/com/metaobjects/metadata/ktx/MetaEndpointKtxTest.kt +++ b/server/java/metadata-ktx/src/test/kotlin/com/metaobjects/metadata/ktx/MetaEndpointKtxTest.kt @@ -24,4 +24,13 @@ class MetaEndpointKtxTest { CanonicalJsonSerializer.canonicalSerializeEffective(loader.root), MetaEndpoint.metaJson(loader.root)) } + + @Test fun `the docs view route is reachable from kotlin and tags its body`() { + val loader = loadString("meta-docs-endpoint-ktx-test", tinyJson) + val docs = MetaEndpoint.docs(loader.root) + assertEquals("/_meta/docs", MetaEndpoint.META_DOCS_ROUTE_PATH) + assertEquals(MetaEndpoint.metaDocsJson(loader.root), docs.body()) + assertEquals(MetaEndpoint.metaDocsEtag(docs.body()), docs.etag()) + kotlin.test.assertTrue(docs.matches(docs.etag())) + } } 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 new file mode 100644 index 0000000000..f7841a89cd --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsView.java @@ -0,0 +1,1006 @@ +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.google.gson.JsonPrimitive; +import com.metaobjects.MetaData; +import com.metaobjects.MetaRoot; +import com.metaobjects.attr.MetaAttribute; +import com.metaobjects.documentation.DocumentationConstants; +import com.metaobjects.field.MetaField; +import com.metaobjects.io.json.CanonicalJsonSerializer; +import com.metaobjects.loader.References; +import com.metaobjects.object.MetaObject; +import com.metaobjects.requirement.MetaRequirement; +import com.metaobjects.requirement.RequirementCheck; +import com.metaobjects.requirement.RequirementClaims; +import com.metaobjects.template.TemplateConstants; +import com.metaobjects.validation.SymbolTable; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +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.TreeMap; +import java.util.TreeSet; + +/** + * The docs view of a loaded model: one port-neutral document, the facts every documentation page + * reads, and what the model explorer draws ({@code docs/features/docs-view.md}). + * + *

    The Java port of TypeScript's {@code buildDocsView} ({@code @metaobjectsdev/metadata}, + * {@code src/docs-view/build.ts}), held to the same bytes by {@code 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 (the canonical serializer's effective + * children, which follow TypeScript's order); inheritance from a child whose parent is another + * node; references from the loader's own resolution ({@link MetaAttribute#getResolvedTarget()}, + * {@link MetaData#getSuperData()}); claims through the resolver the requirement gate uses.

    + * + *

    Three optional inputs add what the model does not hold, each as parsed JSON and each left out + * when {@code null} or malformed: the {@code meta verify --format json} payload, the generation + * manifest ({@code path → { generatedBy, sourceNode }}) and the routes ({@code [{ node, method, + * path }]}). The result is deterministic: {@link #serialize} gives the same bytes for the same + * inputs.

    + */ +public final class DocsView { + + /** Bumped when a field changes meaning or is removed. */ + public static final String FORMAT = "metaobjects-docs-view/1"; + + private static final String CODE_OBJECT_UNCLAIMED = RequirementCheck.WARN_REQUIREMENT_OBJECT_UNCLAIMED; + private static final String EXTENDS = "extends"; + private static final String PKG = MetaData.PKG_SEPARATOR; + private static final String DOT = "."; + private static final String TYPE_SUB = "."; + private static final String NUL = "\u0000"; + + private DocsView() {} + + /** The file's bytes: two-space JSON and one trailing newline. */ + public static String serialize(JsonObject view) { + return DocsViewJson.pretty(view) + "\n"; + } + + /** The docs view of the model alone. */ + public static JsonObject build(MetaRoot root) { + return build(root, null, null, null); + } + + /** + * Build the docs view. {@code verify}, {@code manifest} and {@code routes} are optional + * (null); a malformed one only leaves its part out. + */ + public static JsonObject build(MetaRoot root, JsonElement verify, JsonElement manifest, JsonElement routes) { + return new Build(root).run(verify, manifest, routes); + } + + // ------------------------------------------------------------------ + // the walk + // ------------------------------------------------------------------ + + /** A node as walked: where it sits, and the ids and pages it gets. */ + private static final class Walked { + MetaData md; + String id; + String plain; + Walked top; + Walked parent; + Walked direct; + Walked requirement; + int order; + boolean canonical; + MetaData declaredOn; + String anchor = ""; + String path = ""; + final List children = new ArrayList<>(); + String address = ""; + } + + private record Ledger(String qualifiedPath, String digest, String verdict, JsonArray diagnostics, + String supRef, boolean supResolves, String supTarget, boolean hasSup) {} + + private static final class Build { + final MetaRoot root; + final SymbolTable symbols; + final List walked = new ArrayList<>(); + final List tops = new ArrayList<>(); + final Map byId = new HashMap<>(); + final Map canonical = new IdentityHashMap<>(); + final Map byPlain = new HashMap<>(); + final List requirements = new ArrayList<>(); + final Map holderType = new HashMap<>(); + + Build(MetaRoot root) { + this.root = root; + this.symbols = SymbolTable.build(root); + walk(); + } + + private void walk() { + List topLevel = children(root); + // 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. + Map holder = new HashMap<>(); + for (MetaData md : topLevel) { + String id = plainOf(md); + MetaData held = holder.get(id); + if (held == null || (!MetaObject.TYPE_OBJECT.equals(held.getType()) && MetaObject.TYPE_OBJECT.equals(md.getType()))) { + holder.put(id, md); + } + } + Set seen = new HashSet<>(); + for (int i = 0; i < topLevel.size(); i++) visit(topLevel.get(i), i, null, "", holder, seen); + for (Walked w : walked) w.path = pathOf(w); + } + + private void visit(MetaData md, int index, Walked parent, String reqPrefix, + Map holder, Set seen) { + String name = nameOf(md); + String id; + String plain; + if (parent == null) { + plain = name.isEmpty() ? "#" + index : plainOf(md); + id = plain; + MetaData held = holder.get(plain); + if (!name.isEmpty() && held != md && (held == null || !held.getType().equals(md.getType()))) { + id = qualified(plain, md); + } + } else { + plain = name.isEmpty() ? parent.plain + "#" + index : parent.plain + DOT + name; + id = name.isEmpty() ? parent.id + "#" + index : parent.id + DOT + name; + // The first sibling of a name keeps the plain id; a later one of another type is + // qualified by type. + if (!name.isEmpty() && seen.contains(id)) id = qualified(id, md); + } + if (seen.contains(id)) { + throw new IllegalStateException("docs view: two nodes share the id \"" + id + + "\" — the model names two siblings alike"); + } + seen.add(id); + boolean isReq = MetaRequirement.TYPE_REQUIREMENT.equals(md.getType()); + String address = isReq ? (reqPrefix.isEmpty() ? name : reqPrefix + DOT + name) : reqPrefix; + boolean inherited = parent != null && md.getParent() != parent.md; + Walked w = new Walked(); + w.md = md; + w.id = id; + w.plain = plain; + w.parent = parent; + w.order = index; + w.canonical = parent == null || (parent.canonical && !inherited); + w.declaredOn = inherited ? md.getParent() : null; + w.address = isReq ? address : ""; + w.top = parent == null ? w : parent.top; + w.direct = parent == null ? null : parent.parent == null ? w : parent.direct; + w.requirement = isReq ? w : parent == null ? null : parent.requirement; + if (w.direct == w) w.anchor = memberAnchor(md, name, index); + walked.add(w); + byId.put(id, w); + if (w.top.id.equals(w.top.plain) && !byPlain.containsKey(plain)) byPlain.put(plain, w); + if (w.canonical) canonical.put(md, w); + if (parent == null) tops.add(w); + else parent.children.add(w); + if (isReq) requirements.add(w); + List kids = children(md); + for (int i = 0; i < kids.size(); i++) visit(kids.get(i), i, w, address, holder, seen); + } + + private String pathOf(Walked w) { + if (w.requirement != null) { + Walked r = w.requirement; + return "requirements/" + packageDir(References.effectivePackageOf(r.top.md)) + "/" + pageStem(r.address) + ".html"; + } + Walked top = w.top; + String qualifier = "[" + top.md.getType() + TYPE_SUB + top.md.getSubType() + "]"; + String typed = top.id.endsWith(qualifier) ? "." + top.md.getType() + "-" + top.md.getSubType() : ""; + String page = "model/" + packageDir(References.effectivePackageOf(top.md)) + "/" + pageStem(nameOf(top.md)) + typed + ".html"; + return w.direct == null ? page : page + "#" + w.direct.anchor; + } + + JsonObject link(Walked w) { + String label; + if (w.requirement == w) { + String title = strAttr(w.md, DocumentationConstants.DOC_ATTR_TITLE); + label = title.isEmpty() ? nameOf(w.md) : title; + } else if (w == w.top) { + label = nameOf(w.md); + } else { + label = nameOf(w.top.md) + w.id.substring(w.top.id.length()); + } + JsonObject o = new JsonObject(); + o.addProperty("label", label); + o.addProperty("id", w.id); + o.addProperty("path", w.path); + o.addProperty("kind", w.md.getType() + TYPE_SUB + w.md.getSubType()); + o.addProperty("unresolved", false); + return o; + } + + JsonObject linkTo(MetaData md, String text) { + Walked w = md == null ? null : canonical.get(md); + return w != null ? link(w) : 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. */ + JsonObject refLink(MetaData owner, String value) { + if (owner == null) return unresolved(value); + String tail = References.splitChildTail(value).tail(); + Walked row = tail.isEmpty() ? null : byPlain.get(plainOf(owner) + tail); + return row != null ? link(row) : linkTo(owner, value); + } + + // -------------------------------------------------------------- + // the build + // -------------------------------------------------------------- + + JsonObject run(JsonElement verifyIn, JsonElement manifest, JsonElement routesIn) { + Map> ledger = ledgerRows(verifyIn); + boolean hasVerify = ledger != null; + JsonObject verify = verifyIn != null && verifyIn.isJsonObject() ? verifyIn.getAsJsonObject() : null; + + // ── Requirements: claims first, since nodes and members list them. ── + Map> claimsOn = new IdentityHashMap<>(); + Map reqLinks = new IdentityHashMap<>(); + Map> reqTargets = new IdentityHashMap<>(); + for (Walked r : requirements) { + MetaRequirement req = (MetaRequirement) r.md; + String referrerPkg = RequirementCheck.effectivePackage(req); + JsonArray links = new JsonArray(); + List targets = new ArrayList<>(); + for (String ref : req.getImplementedBy()) { + RequirementClaims.MemberRef split = RequirementClaims.splitMemberRef(ref); + MetaData node = RequirementClaims.resolveClaimTarget(root, symbols, split.owner(), referrerPkg); + MetaData member = node != null && !split.path().isEmpty() ? RequirementClaims.resolveMember(node, split.path()) : node; + String key = node == null ? "" : split.path().isEmpty() ? plainOf(node) : plainOf(node) + DOT + String.join(DOT, split.path()); + Walked w = member != null ? byPlain.get(key) : null; + if (w == null) { + links.add(reqLink(ref, false, unresolved(ref))); + continue; + } + links.add(reqLink(ref, true, link(w))); + targets.add(w); + JsonObject claim = new JsonObject(); + claim.add("requirement", link(r)); + claim.addProperty("member", w == w.top ? "" : memberPath(w)); + claim.addProperty("status", str(req.getStatus())); + claim.add("level", req.getLevel() == null ? JsonNull.INSTANCE : new JsonPrimitive(req.getLevel())); + // The claim is on the top-level node and on every member down to the one it names. + for (Walked x = w; x != null; x = x.parent) claimsOn.computeIfAbsent(x, k -> new ArrayList<>()).add(claim); + } + reqLinks.put(r, links); + reqTargets.put(r, targets); + } + + // ── Files and routes. ── + Map>> filesOf = new IdentityHashMap<>(); + boolean hasManifest = manifest != null && manifest.isJsonObject(); + if (hasManifest) { + for (Map.Entry e : manifest.getAsJsonObject().entrySet()) { + if (!e.getValue().isJsonObject()) continue; + JsonObject entry = e.getValue().getAsJsonObject(); + String sourceNode = stringOrNull(entry, "sourceNode"); + if (sourceNode == null) continue; + Walked w = byPlain.get(sourceNode); + if (w == null) continue; + filesOf.computeIfAbsent(w.top, k -> new LinkedHashMap<>()) + .computeIfAbsent(str(stringOrNull(entry, "generatedBy")), k -> new ArrayList<>()) + .add(e.getKey()); + } + } + Map> routesOf = new IdentityHashMap<>(); + boolean hasRoutes = routesIn != null && routesIn.isJsonArray(); + if (hasRoutes) { + for (JsonElement el : routesIn.getAsJsonArray()) { + if (!el.isJsonObject()) continue; + JsonObject r = el.getAsJsonObject(); + String node = stringOrNull(r, "node"); + String method = stringOrNull(r, "method"); + String path = stringOrNull(r, "path"); + if (node == null || method == null || path == null) continue; + Walked w = byPlain.get(node); + if (w == null) continue; + JsonObject route = new JsonObject(); + // JavaScript's toUpperCase, locale-independent. + route.addProperty("method", method.toUpperCase(java.util.Locale.ROOT)); + route.addProperty("path", path); + routesOf.computeIfAbsent(w.top, k -> new LinkedHashMap<>()) + .put(path + NUL + route.get("method").getAsString(), route); + } + } + + // ── Advisories. ── + JsonArray advisories = new JsonArray(); + Set unclaimedIds = new HashSet<>(); + if (hasVerify && verify != null && verify.has("requirements") && verify.get("requirements").isJsonObject()) { + JsonElement rows = verify.getAsJsonObject("requirements").get("rows"); + if (rows != null && rows.isJsonArray()) { + for (JsonElement el : rows.getAsJsonArray()) { + if (!el.isJsonObject()) continue; + JsonObject d = el.getAsJsonObject(); + String node = str(stringOrNull(d, "node")); + JsonElement subject = node.isEmpty() ? JsonNull.INSTANCE + : byPlain.containsKey(node) ? link(byPlain.get(node).top) : unresolved(node); + JsonObject a = new JsonObject(); + a.addProperty("code", str(stringOrNull(d, "code"))); + a.addProperty("path", str(stringOrNull(d, "path"))); + a.add("subject", subject); + a.addProperty("severity", str(stringOrNull(d, "severity"))); + a.addProperty("source", str(stringOrNull(d, "source"))); + a.addProperty("message", str(stringOrNull(d, "message"))); + advisories.add(a); + if (CODE_OBJECT_UNCLAIMED.equals(a.get("code").getAsString()) && subject.isJsonObject()) { + unclaimedIds.add(subject.getAsJsonObject().get("id").getAsString()); + } + } + } + } + + // ── Members and references. ── + Map> refsFrom = new IdentityHashMap<>(); + List nodes = new ArrayList<>(); + Map> nodeRefs = new IdentityHashMap<>(); + Map nodeById = new HashMap<>(); + for (Walked t : tops) { + AttrsResult ar = attrsOf(t.md); + JsonElement ext = extendsLink(t.md); + JsonArray memberGroups = groupMembers(memberList(t.children, claimsOn, refsFrom)); + List all = new ArrayList<>(); + if (ext.isJsonObject() && !ext.getAsJsonObject().get("unresolved").getAsBoolean()) { + all.add(ref(EXTENDS, JsonNull.INSTANCE, ext.getAsJsonObject())); + } + for (Map.Entry r : ar.refs) all.add(ref(r.getKey(), JsonNull.INSTANCE, r.getValue())); + below(t, refsFrom, all); + nodeRefs.put(t, all); + + JsonArray files = new JsonArray(); + int fileCount = 0; + TreeMap> byGen = new TreeMap<>(filesOf.getOrDefault(t, Map.of())); + for (Map.Entry> g : byGen.entrySet()) { + List paths = new ArrayList<>(g.getValue()); + Collections.sort(paths); + JsonObject fg = new JsonObject(); + fg.addProperty("generatedBy", g.getKey()); + fg.add("paths", strings(paths)); + files.add(fg); + fileCount += paths.size(); + } + JsonArray routes = new JsonArray(); + for (JsonObject r : new TreeMap<>(routesOf.getOrDefault(t, Map.of())).values()) routes.add(r); + + List claims = claimsOn.getOrDefault(t, List.of()); + JsonObject n = new JsonObject(); + n.addProperty("id", t.id); + n.addProperty("name", nameOf(t.md)); + n.addProperty("package", References.effectivePackageOf(t.md)); + n.addProperty("type", t.md.getType()); + n.addProperty("subType", t.md.getSubType()); + n.addProperty("order", t.order); + n.addProperty("path", t.path); + n.addProperty("title", strAttr(t.md, DocumentationConstants.DOC_ATTR_TITLE)); + n.addProperty("description", strAttr(t.md, DocumentationConstants.DOC_ATTR_DESCRIPTION)); + n.addProperty("summary", strAttr(t.md, DocumentationConstants.DOC_ATTR_SUMMARY)); + n.addProperty("abstract", isAbstract(t.md)); + n.add("extends", ext); + n.add("attrs", ar.attrs); + n.add("memberGroups", memberGroups); + n.add("refs", array(all)); + n.add("referencedBy", new JsonArray()); + n.add("claims", array(claims)); + n.add("files", files); + n.add("routes", routes); + n.addProperty("unclaimed", unclaimedIds.contains(t.id)); + JsonObject counts = new JsonObject(); + counts.addProperty("members", t.children.size()); + counts.addProperty("refs", all.size()); + counts.addProperty("referencedBy", 0); + counts.addProperty("claims", claims.size()); + counts.addProperty("files", fileCount); + counts.addProperty("routes", routes.size()); + n.add("counts", counts); + nodes.add(n); + nodeById.put(t.id, n); + } + + // referencedBy: every reference into a top-level node (or a member of it) from another one. + Map> incoming = new LinkedHashMap<>(); + for (Walked t : tops) { + for (JsonObject r : nodeRefs.getOrDefault(t, List.of())) { + JsonObject target = r.getAsJsonObject("target"); + Walked tw = byId.get(target.get("id").getAsString()); + if (tw == null || tw.top == t) continue; + JsonElement via = r.get("via"); + JsonObject referrer = new JsonObject(); + referrer.addProperty("attr", r.get("attr").getAsString()); + referrer.add("from", link(t)); + referrer.add("via", via); + referrer.add("target", target); + String viaId = via.isJsonObject() ? via.getAsJsonObject().get("id").getAsString() : ""; + String key = String.join(NUL, t.id, r.get("attr").getAsString(), viaId, target.get("id").getAsString()); + incoming.computeIfAbsent(tw.top.id, k -> new HashMap<>()).put(key, referrer); + } + } + for (Map.Entry> e : incoming.entrySet()) { + JsonObject n = nodeById.get(e.getKey()); + if (n == null) continue; + JsonArray by = new JsonArray(); + for (JsonObject r : new TreeMap<>(e.getValue()).values()) by.add(r); + n.add("referencedBy", by); + n.getAsJsonObject("counts").addProperty("referencedBy", by.size()); + } + nodes.sort((a, c) -> a.get("id").getAsString().compareTo(c.get("id").getAsString())); + + // ── The requirement list, flat, in document order. ── + Map> reqChildren = new IdentityHashMap<>(); + for (Walked r : requirements) { + Walked p = reqParent(r); + if (p != null) reqChildren.computeIfAbsent(p, k -> new ArrayList<>()).add(r); + } + List reqs = new ArrayList<>(); + for (Walked r : requirements) { + MetaRequirement req = (MetaRequirement) r.md; + String pkg = RequirementCheck.effectivePackage(req); + String qualifiedPath = pkg.isEmpty() ? r.address : pkg + PKG + r.address; + Deque rows = ledger == null ? null : ledger.get(qualifiedPath); + Ledger row = rows == null ? null : rows.poll(); + List chain = new ArrayList<>(); + for (Walked p = reqParent(r); p != null; p = reqParent(p)) chain.add(0, p); + List sub = new ArrayList<>(); + subtree(r, reqChildren, sub); + List linked = new ArrayList<>(); + for (Walked x : sub) { + MetaRequirement xr = (MetaRequirement) x.md; + Integer level = xr.getLevel(); + if ((level == null ? 0 : level) >= MetaRequirement.LEVEL_OBJECT + || (level == null && !xr.getImplementedBy().isEmpty())) { + linked.add(x); + } + } + List counted = linked.isEmpty() ? List.of(r) : linked; + List statuses = new ArrayList<>(); + for (Walked x : counted) { + String s = str(((MetaRequirement) x.md).getStatus()); + if (!s.isEmpty()) statuses.add(s); + } + TreeMap targetTops = new TreeMap<>(); + for (Walked x : sub) for (Walked w : reqTargets.getOrDefault(x, List.of())) targetTops.putIfAbsent(w.top.id, w.top); + List children = reqChildren.getOrDefault(r, List.of()); + + JsonObject o = new JsonObject(); + o.addProperty("id", r.id); + o.addProperty("name", nameOf(r.md)); + o.addProperty("label", link(r).get("label").getAsString()); + o.addProperty("path", r.path); + o.addProperty("address", r.address); + o.addProperty("package", pkg); + o.addProperty("qualifiedPath", qualifiedPath); + o.addProperty("subType", r.md.getSubType()); + o.add("level", req.getLevel() == null ? JsonNull.INSTANCE : new JsonPrimitive(req.getLevel())); + o.addProperty("status", str(req.getStatus())); + o.addProperty("disposition", str(req.getDisposition())); + o.addProperty("statement", strAttr(req, MetaRequirement.ATTR_STATEMENT)); + o.addProperty("counterexample", strAttr(req, MetaRequirement.ATTR_COUNTEREXAMPLE)); + o.addProperty("title", strAttr(req, DocumentationConstants.DOC_ATTR_TITLE)); + o.addProperty("description", strAttr(req, DocumentationConstants.DOC_ATTR_DESCRIPTION)); + o.add("trackedBy", strings(req.getTrackedBy())); + o.addProperty("depth", chain.size()); + o.add("parent", chain.isEmpty() ? JsonNull.INSTANCE : link(chain.get(chain.size() - 1))); + JsonArray crumbs = new JsonArray(); + for (Walked x : chain) crumbs.add(link(x)); + o.add("breadcrumbs", crumbs); + JsonArray kids = new JsonArray(); + for (Walked x : children) kids.add(link(x)); + o.add("children", kids); + o.add("implementedBy", reqLinks.getOrDefault(r, new JsonArray())); + if (row == null || !row.hasSup()) { + o.add("supersededBy", JsonNull.INSTANCE); + } else { + Walked supTarget = null; + if (!row.supTarget().isEmpty()) { + for (Walked x : requirements) { + String p = RequirementCheck.effectivePackage(x.md); + if ((p.isEmpty() ? x.address : p + PKG + x.address).equals(row.supTarget())) { supTarget = x; break; } + } + } + o.add("supersededBy", reqLink(row.supRef(), row.supResolves(), supTarget != null ? link(supTarget) : unresolved(row.supRef()))); + } + o.addProperty("inLedger", row != null); + o.addProperty("verdict", row == null ? "" : row.verdict()); + o.addProperty("digest", row == null ? "" : row.digest()); + o.add("diagnostics", row == null ? new JsonArray() : row.diagnostics()); + o.add("rollup", statusCounts(statuses)); + o.addProperty("rollupTotal", statuses.size()); + o.addProperty("belowCount", sub.size() - 1); + o.addProperty("childCount", children.size()); + JsonArray targets = new JsonArray(); + for (Walked w : targetTops.values()) targets.add(link(w)); + o.add("targets", targets); + o.addProperty("targetCount", targetTops.size()); + reqs.add(o); + } + + // ── Packages, counts, slices. ── + TreeSet pkgNames = new TreeSet<>(); + for (JsonObject n : nodes) pkgNames.add(n.get("package").getAsString()); + JsonArray packages = new JsonArray(); + for (String name : pkgNames) { + TreeMap groups = new TreeMap<>(); + int count = 0; + for (JsonObject n : nodes) { + if (!n.get("package").getAsString().equals(name)) continue; + count++; + String type = n.get("type").getAsString(); + String subType = n.get("subType").getAsString(); + JsonObject g = groups.computeIfAbsent(type + TYPE_SUB + subType, k -> { + JsonObject x = new JsonObject(); + x.addProperty("type", type); + x.addProperty("subType", subType); + x.addProperty("count", 0); + x.add("nodes", new JsonArray()); + return x; + }); + g.addProperty("count", g.get("count").getAsInt() + 1); + g.getAsJsonArray("nodes").add(link(byId.get(n.get("id").getAsString()))); + } + JsonObject p = new JsonObject(); + p.addProperty("name", name); + p.addProperty("count", count); + p.add("groups", array(new ArrayList<>(groups.values()))); + packages.add(p); + } + + JsonObject vc = verify != null && verify.has("requirementCounts") && verify.get("requirementCounts").isJsonObject() + ? verify.getAsJsonObject("requirementCounts") : null; + Set allFiles = new HashSet<>(); + int routeCount = 0; + for (JsonObject n : nodes) { + for (JsonElement g : n.getAsJsonArray("files")) for (JsonElement p : g.getAsJsonObject().getAsJsonArray("paths")) allFiles.add(p.getAsString()); + routeCount += n.getAsJsonArray("routes").size(); + } + int functional = 0; + int architectural = 0; + int claimCount = 0; + List reqStatuses = new ArrayList<>(); + for (JsonObject r : reqs) { + String st = r.get("subType").getAsString(); + if (MetaRequirement.SUBTYPE_FUNCTIONAL.equals(st)) functional++; + if (MetaRequirement.SUBTYPE_ARCHITECTURAL.equals(st)) architectural++; + reqStatuses.add(r.get("status").getAsString()); + for (JsonElement l : r.getAsJsonArray("implementedBy")) if (l.getAsJsonObject().get("resolves").getAsBoolean()) claimCount++; + } + JsonObject counts = new JsonObject(); + counts.addProperty("nodes", nodes.size()); + counts.addProperty("packages", packages.size()); + counts.addProperty("requirements", reqs.size()); + counts.addProperty("functional", functional); + counts.addProperty("architectural", architectural); + counts.add("byStatus", statusCounts(reqStatuses)); + counts.addProperty("claims", claimCount); + counts.addProperty("files", allFiles.size()); + counts.addProperty("routes", routeCount); + counts.add("undecided", num(vc, "undecided")); + counts.addProperty("coverageMeasured", isNumber(vc, "entitiesTotal")); + counts.add("entitiesClaimed", num(vc, "entitiesClaimed")); + counts.add("entitiesTotal", num(vc, "entitiesTotal")); + + JsonObject sources = new JsonObject(); + sources.addProperty("requirements", hasVerify); + sources.addProperty("files", hasManifest); + sources.addProperty("routes", hasRoutes); + + JsonObject view = new JsonObject(); + view.addProperty("format", FORMAT); + view.add("sources", sources); + view.add("counts", counts); + view.add("packages", packages); + view.add("nodes", array(nodes)); + view.add("requirements", array(reqs)); + view.add("advisories", advisories); + view.add("slices", slices(nodes, reqs)); + return view; + } + + private JsonArray slices(List nodes, List reqs) { + List slices = new ArrayList<>(); + TreeSet pkgs = new TreeSet<>(); + for (JsonObject n : nodes) pkgs.add(n.get("package").getAsString()); + for (String pkg : pkgs) { + TreeSet ids = new TreeSet<>(); + for (JsonObject n : nodes) if (n.get("package").getAsString().equals(pkg)) ids.add(n.get("id").getAsString()); + slices.add(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. + Map reqById = new HashMap<>(); + for (JsonObject r : reqs) reqById.put(r.get("id").getAsString(), r); + for (JsonObject r : reqs) { + if (r.get("childCount").getAsInt() == 0) continue; + TreeSet ids = new TreeSet<>(); + sliceVisit(r, reqById, ids); + slices.add(slice("requirement", r.get("id").getAsString(), ids)); + } + // A template: itself and what its own attributes reference. + for (JsonObject n : nodes) { + if (!TemplateConstants.TYPE_TEMPLATE.equals(n.get("type").getAsString())) continue; + TreeSet ids = new TreeSet<>(); + ids.add(n.get("id").getAsString()); + for (JsonElement el : n.getAsJsonArray("refs")) { + JsonObject r = el.getAsJsonObject(); + if (!r.get("via").isJsonNull()) continue; + String tid = r.getAsJsonObject("target").get("id").getAsString(); + Walked w = byId.get(tid); + ids.add(w != null ? w.top.id : tid); + } + slices.add(slice("prompt", n.get("id").getAsString(), ids)); + } + slices.sort((a, c) -> a.get("id").getAsString().compareTo(c.get("id").getAsString())); + return array(slices); + } + + private void sliceVisit(JsonObject x, Map reqById, Set ids) { + ids.add(x.get("id").getAsString()); + for (JsonElement el : x.getAsJsonArray("implementedBy")) { + JsonObject l = el.getAsJsonObject(); + if (!l.get("resolves").getAsBoolean()) continue; + String tid = l.getAsJsonObject("target").get("id").getAsString(); + ids.add(tid); + Walked w = byId.get(tid); + if (w != null) ids.add(w.top.id); + } + for (JsonElement c : x.getAsJsonArray("children")) { + JsonObject child = reqById.get(c.getAsJsonObject().get("id").getAsString()); + if (child != null) sliceVisit(child, reqById, ids); + } + } + + private static JsonObject slice(String kind, String anchor, Set ids) { + JsonObject s = new JsonObject(); + s.addProperty("id", kind + ":" + anchor); + s.addProperty("kind", kind); + s.addProperty("anchor", anchor); + s.add("nodes", strings(new ArrayList<>(ids))); + return s; + } + + private Walked reqParent(Walked r) { + return r.parent == null ? null : r.parent.requirement; + } + + private void subtree(Walked r, Map> reqChildren, List out) { + out.add(r); + for (Walked c : reqChildren.getOrDefault(r, List.of())) subtree(c, reqChildren, out); + } + + private void below(Walked w, Map> refsFrom, List all) { + for (Walked c : w.children) { + all.addAll(refsFrom.getOrDefault(c, List.of())); + below(c, refsFrom, all); + } + } + + private List memberList(List ws, Map> claimsOn, + Map> refsFrom) { + List out = new ArrayList<>(); + for (Walked w : ws) out.add(member(w, claimsOn, refsFrom)); + return out; + } + + private JsonObject member(Walked w, Map> claimsOn, Map> refsFrom) { + AttrsResult ar = attrsOf(w.md); + JsonElement ext = extendsLink(w.md); + List own = new ArrayList<>(); + if (ext.isJsonObject() && !ext.getAsJsonObject().get("unresolved").getAsBoolean()) { + own.add(ref(EXTENDS, link(w), ext.getAsJsonObject())); + } + for (Map.Entry r : ar.refs) own.add(ref(r.getKey(), link(w), r.getValue())); + refsFrom.put(w, own); + JsonObject m = new JsonObject(); + m.addProperty("id", w.id); + m.addProperty("name", nameOf(w.md)); + m.addProperty("type", w.md.getType()); + m.addProperty("subType", w.md.getSubType()); + m.addProperty("order", w.order); + m.addProperty("anchor", w.anchor); + m.addProperty("path", w.path); + m.addProperty("abstract", isAbstract(w.md)); + m.addProperty("isArray", w.md instanceof MetaField && ((MetaField) w.md).isArrayType()); + m.add("extends", ext); + m.add("declaredOn", w.declaredOn != null ? linkTo(w.declaredOn, nameOf(w.declaredOn)) : JsonNull.INSTANCE); + m.add("attrs", ar.attrs); + m.add("refs", array(own)); + m.add("claims", array(claimsOn.getOrDefault(w, List.of()))); + m.add("memberGroups", groupMembers(memberList(w.children, claimsOn, refsFrom))); + return m; + } + + private JsonElement extendsLink(MetaData md) { + MetaData sup = md.hasSuperData() ? md.getSuperData() : null; + String superRef = md.getAuthoredSuperRef(); + if (sup == null && superRef == null) return JsonNull.INSTANCE; + return linkTo(sup, superRef == null ? "" : superRef); + } + + private record AttrsResult(JsonArray attrs, List> refs) {} + + /** A node's effective attributes, by name, each value linked where the loader resolved it. */ + private AttrsResult attrsOf(MetaData md) { + JsonArray attrs = new JsonArray(); + List> refs = new ArrayList<>(); + TreeMap byName = new TreeMap<>(); + for (MetaAttribute a : effectiveAttrs(md)) byName.putIfAbsent(a.getName(), a); + for (Map.Entry e : byName.entrySet()) { + String name = e.getKey(); + JsonElement value = canonicalValue(CanonicalJsonSerializer.attrValueToJson(e.getValue())); + boolean isRef = References.isRefBearingAttr(md, name); + Object resolved = isRef ? declaringResolvedTarget(md, name) : null; + JsonArray values = new JsonArray(); + if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString()) { + String text = value.getAsString(); + JsonElement link = isRef ? refLink(resolved instanceof MetaData ? (MetaData) resolved : null, text) : JsonNull.INSTANCE; + values.add(attrValue(text, link)); + if (link.isJsonObject() && !link.getAsJsonObject().get("unresolved").getAsBoolean()) refs.add(Map.entry(name, link.getAsJsonObject())); + } else if (value.isJsonArray() && allStrings(value.getAsJsonArray())) { + JsonArray arr = value.getAsJsonArray(); + for (int i = 0; i < arr.size(); i++) { + String item = arr.get(i).getAsString(); + MetaData owner = null; + if (resolved instanceof List list && i < list.size() && list.get(i) instanceof MetaData md2) owner = md2; + JsonElement link = isRef ? refLink(owner, item) : JsonNull.INSTANCE; + values.add(attrValue(item, link)); + if (link.isJsonObject() && !link.getAsJsonObject().get("unresolved").getAsBoolean()) refs.add(Map.entry(name, link.getAsJsonObject())); + } + } else { + values.add(attrValue(DocsViewJson.compact(value), JsonNull.INSTANCE)); + } + JsonObject a = new JsonObject(); + a.addProperty("name", name); + a.add("value", value); + a.add("values", values); + attrs.add(a); + } + return new AttrsResult(attrs, refs); + } + } + + // ------------------------------------------------------------------ + // helpers + // ------------------------------------------------------------------ + + /** The node's effective structural children (attributes excluded), in TypeScript's order. */ + private static List children(MetaData md) { + return CanonicalJsonSerializer.collectEffectiveStructuralChildren(md); + } + + /** + * The node's effective attributes: own plus inherited through {@code extends}, own winning. + * {@code isAbstract} and {@code isArray} are native flags in the view (as in TypeScript), so + * they are not attributes here. + */ + private static List effectiveAttrs(MetaData md) { + List out = new ArrayList<>(); + for (MetaAttribute a : md.getMetaAttrs(true)) { + String n = a.getName(); + if (MetaData.ATTR_IS_ABSTRACT.equals(n) || MetaField.ATTR_IS_ARRAY.equals(n)) continue; + out.add(a); + } + return out; + } + + /** What the loader bound for {@code name} on the layer that declares it (own, else the + * nearest {@code extends} ancestor). */ + private static Object declaringResolvedTarget(MetaData md, String name) { + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + for (MetaData n = md; n != null && seen.add(n); n = n.hasSuperData() ? n.getSuperData() : null) { + // ADR-0039: own — locating the layer that declares the attr, walking the super chain. + if (n.hasMetaAttr(name, false)) return n.getMetaAttr(name, false).getResolvedTarget(); + } + return null; + } + + /** The name as the view states it: {@code ""} for one the parser generated. */ + private static String nameOf(MetaData md) { + if (CanonicalJsonSerializer.isAutoGeneratedName(md)) return ""; + String s = md.getShortName(); + return s == null ? "" : s; + } + + private static String plainOf(MetaData md) { + String pkg = References.effectivePackageOf(md); + return pkg.isEmpty() ? nameOf(md) : pkg + PKG + nameOf(md); + } + + private 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()); + } + + private static String strAttr(MetaData md, String name) { + if (!md.hasMetaAttr(name)) return ""; + Object v = md.getMetaAttr(name).getValue(); + return v instanceof String s ? s : ""; + } + + private static String qualified(String id, MetaData md) { + return id + "[" + md.getType() + TYPE_SUB + md.getSubType() + "]"; + } + + /** {@code m-} for a field, {@code m--} for anything else, {@code m--} with no name. */ + private static String memberAnchor(MetaData md, String name, int order) { + if (name.isEmpty()) return "m-" + md.getType() + "-" + order; + return MetaField.TYPE_FIELD.equals(md.getType()) ? "m-" + name : "m-" + md.getType() + "-" + name; + } + + /** A member's id after its top-level node's. */ + private static String memberPath(Walked w) { + String rest = w.id.substring(w.top.id.length()); + return rest.startsWith(DOT) ? rest.substring(DOT.length()) : rest; + } + + private static String packageDir(String pkg) { + return pkg.isEmpty() ? "-root" : String.join("/", pkg.split(PKG, -1)); + } + + private static String pageStem(String name) { + return name.toLowerCase(java.util.Locale.ROOT).equals("index") ? name + ".node" : name; + } + + private static JsonObject unresolved(String text) { + JsonObject o = new JsonObject(); + o.addProperty("label", text); + o.addProperty("id", ""); + o.addProperty("path", ""); + o.addProperty("kind", ""); + o.addProperty("unresolved", true); + return o; + } + + private static JsonObject reqLink(String ref, boolean resolves, JsonObject target) { + JsonObject o = new JsonObject(); + o.addProperty("ref", ref); + o.addProperty("resolves", resolves); + o.add("target", target); + return o; + } + + private static JsonObject ref(String attr, JsonElement via, JsonObject target) { + JsonObject o = new JsonObject(); + o.addProperty("attr", attr); + o.add("via", via); + o.add("target", target); + return o; + } + + private static JsonObject attrValue(String text, JsonElement link) { + JsonObject o = new JsonObject(); + o.addProperty("text", text); + o.add("link", link); + return o; + } + + private static JsonArray groupMembers(List members) { + LinkedHashMap groups = new LinkedHashMap<>(); + for (JsonObject m : members) { + JsonObject g = groups.computeIfAbsent(m.get("type").getAsString(), t -> { + JsonObject x = new JsonObject(); + x.addProperty("type", t); + x.addProperty("count", 0); + x.add("members", new JsonArray()); + return x; + }); + g.addProperty("count", g.get("count").getAsInt() + 1); + g.getAsJsonArray("members").add(m); + } + return array(new ArrayList<>(groups.values())); + } + + private static JsonArray statusCounts(List statuses) { + JsonArray out = new JsonArray(); + for (String status : MetaRequirement.STATUSES) { + int count = 0; + for (String s : statuses) if (s.equals(status)) count++; + JsonObject o = new JsonObject(); + o.addProperty("status", status); + o.addProperty("count", count); + out.add(o); + } + return out; + } + + private static Map> ledgerRows(JsonElement verify) { + if (verify == null || !verify.isJsonObject()) return null; + JsonElement led = verify.getAsJsonObject().get("requirementLedger"); + if (led == null || !led.isJsonArray()) return null; + Map> out = new HashMap<>(); + for (JsonElement el : led.getAsJsonArray()) { + if (!el.isJsonObject()) continue; + JsonObject raw = el.getAsJsonObject(); + String qp = stringOrNull(raw, "qualifiedPath"); + if (qp == null) continue; + JsonArray diags = new JsonArray(); + JsonElement ds = raw.get("diagnostics"); + if (ds != null && ds.isJsonArray()) { + for (JsonElement d : ds.getAsJsonArray()) { + if (!d.isJsonObject()) continue; + JsonObject dobj = d.getAsJsonObject(); + JsonObject o = new JsonObject(); + for (String k : List.of("code", "severity", "source", "message")) o.addProperty(k, str(stringOrNull(dobj, k))); + diags.add(o); + } + } + JsonElement supEl = raw.get("supersededBy"); + boolean hasSup = supEl != null && supEl.isJsonObject() && stringOrNull(supEl.getAsJsonObject(), "ref") != null; + JsonObject sup = hasSup ? supEl.getAsJsonObject() : new JsonObject(); + JsonElement res = sup.get("resolves"); + Ledger row = new Ledger(qp, str(stringOrNull(raw, "digest")), str(stringOrNull(raw, "verdict")), diags, + str(stringOrNull(sup, "ref")), + res != null && res.isJsonPrimitive() && res.getAsJsonPrimitive().isBoolean() && res.getAsBoolean(), + str(stringOrNull(sup, "target")), hasSup); + out.computeIfAbsent(qp, k -> new ArrayDeque<>()).add(row); + } + return out; + } + + /** A value with every object's keys in code-unit order, as the canonical serializer writes them. */ + private static JsonElement canonicalValue(JsonElement v) { + if (v == null || v.isJsonNull()) return JsonNull.INSTANCE; + if (v.isJsonArray()) { + JsonArray out = new JsonArray(); + for (JsonElement e : v.getAsJsonArray()) out.add(canonicalValue(e)); + return out; + } + if (v.isJsonObject()) { + JsonObject out = new JsonObject(); + for (Map.Entry e : new TreeMap<>(v.getAsJsonObject().asMap()).entrySet()) { + out.add(e.getKey(), canonicalValue(e.getValue())); + } + return out; + } + return v; + } + + private static boolean allStrings(JsonArray arr) { + for (JsonElement e : arr) if (!e.isJsonPrimitive() || !e.getAsJsonPrimitive().isString()) return false; + return true; + } + + private static String stringOrNull(JsonObject o, String key) { + JsonElement e = o.get(key); + return e != null && e.isJsonPrimitive() && e.getAsJsonPrimitive().isString() ? e.getAsString() : null; + } + + private static boolean isNumber(JsonObject o, String key) { + if (o == null) return false; + JsonElement e = o.get(key); + return e != null && e.isJsonPrimitive() && e.getAsJsonPrimitive().isNumber(); + } + + private static JsonElement num(JsonObject o, String key) { + return isNumber(o, key) ? o.get(key) : new JsonPrimitive(0); + } + + private static String str(String s) { + return s == null ? "" : s; + } + + private static JsonArray strings(List items) { + JsonArray out = new JsonArray(); + for (String s : items) out.add(s); + return out; + } + + private static JsonArray array(List items) { + JsonArray out = new JsonArray(); + for (JsonObject o : items) out.add(o); + return out; + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsViewJson.java b/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsViewJson.java new file mode 100644 index 0000000000..46dbf09119 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/docsview/DocsViewJson.java @@ -0,0 +1,173 @@ +package com.metaobjects.docsview; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Map; + +/** + * JSON text exactly as JavaScript's {@code JSON.stringify} writes it, which is what the docs view + * contract states its bytes in ({@code docs/features/docs-view.md}): {@link #pretty} is + * {@code JSON.stringify(v, null, 2)}, {@link #compact} is {@code JSON.stringify(v)}. + * + *

    Gson's own writer differs in the places that matter for byte parity: it escapes HTML + * characters and the line separators, and it writes a double as {@code 3.0}. This writer escapes + * only what {@code JSON.stringify} escapes (the quote, the backslash, control characters and lone + * surrogates) and writes a number as a JavaScript {@code Number} prints.

    + */ +public final class DocsViewJson { + + private DocsViewJson() {} + + /** Two-space indented JSON, as {@code JSON.stringify(v, null, 2)}. */ + public static String pretty(JsonElement value) { + StringBuilder out = new StringBuilder(); + write(out, value, "", true); + return out.toString(); + } + + /** JSON with no whitespace, as {@code JSON.stringify(v)}. */ + public static String compact(JsonElement value) { + StringBuilder out = new StringBuilder(); + write(out, value, "", false); + return out.toString(); + } + + /** A string as a JSON string literal, as {@code JSON.stringify(s)}. */ + public static String quote(String s) { + StringBuilder out = new StringBuilder(s.length() + 2); + writeString(out, s); + return out.toString(); + } + + private static void write(StringBuilder out, JsonElement value, String indent, boolean pretty) { + if (value == null || value.isJsonNull()) { + out.append("null"); + } else if (value.isJsonObject()) { + JsonObject obj = value.getAsJsonObject(); + if (obj.size() == 0) { + out.append("{}"); + return; + } + String inner = indent + " "; + out.append('{'); + boolean first = true; + for (Map.Entry e : obj.entrySet()) { + if (!first) out.append(','); + first = false; + if (pretty) out.append('\n').append(inner); + writeString(out, e.getKey()); + out.append(pretty ? ": " : ":"); + write(out, e.getValue(), inner, pretty); + } + if (pretty) out.append('\n').append(indent); + out.append('}'); + } else if (value.isJsonArray()) { + JsonArray arr = value.getAsJsonArray(); + if (arr.isEmpty()) { + out.append("[]"); + return; + } + String inner = indent + " "; + out.append('['); + for (int i = 0; i < arr.size(); i++) { + if (i > 0) out.append(','); + if (pretty) out.append('\n').append(inner); + write(out, arr.get(i), inner, pretty); + } + if (pretty) out.append('\n').append(indent); + out.append(']'); + } else { + JsonPrimitive p = value.getAsJsonPrimitive(); + if (p.isBoolean()) out.append(p.getAsBoolean()); + else if (p.isNumber()) out.append(number(p.getAsNumber())); + else writeString(out, p.getAsString()); + } + } + + private static void writeString(StringBuilder out, String s) { + out.append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + switch (c) { + case '"' -> out.append("\\\""); + case '\\' -> out.append("\\\\"); + case '\b' -> out.append("\\b"); + case '\f' -> out.append("\\f"); + case '\n' -> out.append("\\n"); + case '\r' -> out.append("\\r"); + case '\t' -> out.append("\\t"); + default -> { + if (c < 0x20) { + unicodeEscape(out, c); + } else if (Character.isHighSurrogate(c)) { + if (i + 1 < s.length() && Character.isLowSurrogate(s.charAt(i + 1))) { + out.append(c).append(s.charAt(++i)); + } else { + unicodeEscape(out, c); + } + } else if (Character.isLowSurrogate(c)) { + unicodeEscape(out, c); + } else { + out.append(c); + } + } + } + } + out.append('"'); + } + + private static void unicodeEscape(StringBuilder out, char c) { + out.append("\\u"); + String hex = Integer.toHexString(c); + for (int k = hex.length(); k < 4; k++) out.append('0'); + out.append(hex); + } + + /** A number as JavaScript's {@code Number.prototype.toString} writes it. */ + static String number(Number n) { + if (n instanceof Integer || n instanceof Long || n instanceof Short || n instanceof Byte) { + long v = n.longValue(); + // A JavaScript number holds integers exactly up to 2^53; beyond that it prints the + // nearest double, as JSON.parse would have read it. + if (Math.abs(v) <= (1L << 53)) return Long.toString(v); + return number((double) v); + } + if (n instanceof BigInteger || n instanceof BigDecimal) return number(n.doubleValue()); + double d = n.doubleValue(); + return number(d); + } + + private static String number(double d) { + if (Double.isNaN(d) || Double.isInfinite(d)) return "null"; + if (d == 0) return "0"; + // Double.toString gives the shortest digits that round-trip (JDK 19+), as JavaScript does. + BigDecimal exact = new BigDecimal(Double.toString(Math.abs(d))).stripTrailingZeros(); + String digits = exact.unscaledValue().toString(); + int k = digits.length(); + // The decimal exponent n of ECMA-262 Number::toString: value = 0.digits x 10^n. + int e = k - exact.scale(); + StringBuilder out = new StringBuilder(); + if (d < 0) out.append('-'); + if (k <= e && e <= 21) { + out.append(digits); + for (int i = 0; i < e - k; i++) out.append('0'); + } else if (0 < e && e <= 21) { + out.append(digits, 0, e).append('.').append(digits, e, k); + } else if (-6 < e && e <= 0) { + out.append("0."); + for (int i = 0; i < -e; i++) out.append('0'); + out.append(digits); + } else { + int exp = e - 1; + out.append(digits.charAt(0)); + if (k > 1) out.append('.').append(digits, 1, k); + out.append('e').append(exp < 0 ? '-' : '+').append(Math.abs(exp)); + } + return out.toString(); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/io/json/CanonicalJsonSerializer.java b/server/java/metadata/src/main/java/com/metaobjects/io/json/CanonicalJsonSerializer.java index 07e08dbc75..dbd430147f 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/io/json/CanonicalJsonSerializer.java +++ b/server/java/metadata/src/main/java/com/metaobjects/io/json/CanonicalJsonSerializer.java @@ -541,7 +541,7 @@ private static List collectOwnStructuralChildren(MetaData node) { * type+name but lists own children first, which diverges from the oracle — * hence this explicit recursive merge.

    */ - private static List collectEffectiveStructuralChildren(MetaData node) { + public static List collectEffectiveStructuralChildren(MetaData node) { return effectiveChildrenMerged(node, new java.util.IdentityHashMap<>()); } @@ -730,7 +730,7 @@ private static boolean getNativeIsArray(MetaData node, boolean effective) { * auto-naming types ({@link BaseMetaDataParser#isAutoNamingType}) can carry a * synthesised name; an empty name is the degenerate "no name" case.

    */ - private static boolean isAutoGeneratedName(MetaData node) { + public static boolean isAutoGeneratedName(MetaData node) { if (!BaseMetaDataParser.isAutoNamingType(node.getType())) { return false; } @@ -766,7 +766,7 @@ private static boolean isAutoGeneratedName(MetaData node) { * */ @SuppressWarnings({"unchecked", "rawtypes"}) - private static JsonElement attrValueToJson(MetaAttribute attr) { + public static JsonElement attrValueToJson(MetaAttribute attr) { Object value = attr.getValue(); // OBJECT-datatype attr with a Map value: emit as a JSON object. diff --git a/server/java/metadata/src/main/java/com/metaobjects/io/json/MetaEndpoint.java b/server/java/metadata/src/main/java/com/metaobjects/io/json/MetaEndpoint.java index 482f884eeb..e116336b80 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/io/json/MetaEndpoint.java +++ b/server/java/metadata/src/main/java/com/metaobjects/io/json/MetaEndpoint.java @@ -1,6 +1,9 @@ package com.metaobjects.io.json; +import com.google.gson.JsonElement; import com.metaobjects.MetaData; +import com.metaobjects.MetaRoot; +import com.metaobjects.docsview.DocsView; /** * UI-1 — the metadata API contract. @@ -17,6 +20,21 @@ * *

    Guard that route with your own authorization — {@code /_meta} publishes the * shape of the model, though no row data. + * + *

    Beside it, {@link #META_DOCS_ROUTE_PATH} serves the same model as its docs view, the + * document the model explorer reads ({@code docs/features/metadata-api.md}). Build one + * {@link Docs} per loaded model, keep it, and answer from it: + * + *

    + * private final MetaEndpoint.Docs docs = MetaEndpoint.docs(root);
    + *
    + * @GetMapping("/api" + MetaEndpoint.META_DOCS_ROUTE_PATH)
    + * public ResponseEntity<String> docs(@RequestHeader(value = "If-None-Match", required = false) String tag) {
    + *   var ok = docs.matches(tag) ? ResponseEntity.status(HttpStatus.NOT_MODIFIED) : ResponseEntity.ok();
    + *   ok.eTag(docs.etag()).cacheControl(CacheControl.noCache()).contentType(MediaType.APPLICATION_JSON);
    + *   return docs.matches(tag) ? ok.build() : ok.body(docs.body());
    + * }
    + * 
    */ public final class MetaEndpoint { @@ -35,4 +53,80 @@ private MetaEndpoint() {} public static String metaJson(MetaData root) { return CanonicalJsonSerializer.canonicalSerializeEffective(root); } + + /** + * The docs view endpoint's path, mounted under the host's API prefix beside + * {@link #META_ROUTE_PATH}. A cross-port contract value: the model explorer reads + * {@code GET {apiPrefix}/_meta/docs} from any backend. + */ + public static final String META_DOCS_ROUTE_PATH = META_ROUTE_PATH + "/docs"; + + /** + * The {@code GET {apiPrefix}/_meta/docs} response body: the loaded model's docs view, built + * from the model alone (no verify payload, no generation manifest, which a running + * application does not hold), with the same bytes every port writes for the same model. + */ + public static String metaDocsJson(MetaRoot root) { + return metaDocsJson(root, null); + } + + /** {@link #metaDocsJson(MetaRoot)} with the routes the application mounts + * ({@code [{ node, method, path }]}, {@code node} a resolution key), listed on each node. */ + public static String metaDocsJson(MetaRoot root, JsonElement routes) { + return DocsView.serialize(DocsView.build(root, null, null, routes)); + } + + /** The docs view of one loaded model, built once: the model is immutable after load. */ + public static Docs docs(MetaRoot root) { + return new Docs(metaDocsJson(root)); + } + + /** {@link #docs(MetaRoot)} with the application's routes. */ + public static Docs docs(MetaRoot root, JsonElement routes) { + return new Docs(metaDocsJson(root, routes)); + } + + /** A built docs view body and its strong {@code ETag}. */ + public static final class Docs { + private final String body; + private final String etag; + + private Docs(String body) { + this.body = body; + this.etag = metaDocsEtag(body); + } + + public String body() { return body; } + + public String etag() { return etag; } + + /** Whether an {@code If-None-Match} value names this body's tag (or is {@code *}): answer 304. */ + public boolean matches(String ifNoneMatch) { return etagMatches(ifNoneMatch, 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 same value TypeScript's mount sends. The contract is only that the + * tag changes when the body does; a client compares it and never parses it. + */ + public static String metaDocsEtag(String body) { + int h = 0x811c9dc5; + for (int i = 0; i < body.length(); i++) { + h ^= body.charAt(i); + h *= 0x01000193; + } + String hex = Integer.toHexString(h); + return "\"" + Integer.toHexString(body.length()) + "-" + "0".repeat(8 - hex.length()) + hex + "\""; + } + + /** Whether an {@code If-None-Match} header value names {@code etag} (or is {@code *}). */ + public static boolean etagMatches(String ifNoneMatch, String etag) { + if (ifNoneMatch == null || ifNoneMatch.isEmpty()) return false; + for (String t : ifNoneMatch.split(",")) { + String v = t.trim(); + if (v.startsWith("W/")) v = v.substring(2); + if (v.equals("*") || v.equals(etag)) return true; + } + return false; + } } diff --git a/server/java/metadata/src/test/java/com/metaobjects/docsview/DocsViewConformanceTest.java b/server/java/metadata/src/test/java/com/metaobjects/docsview/DocsViewConformanceTest.java new file mode 100644 index 0000000000..25b7c81612 --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/docsview/DocsViewConformanceTest.java @@ -0,0 +1,157 @@ +package com.metaobjects.docsview; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.MetaData; +import com.metaobjects.MetaRoot; +import com.metaobjects.attr.MetaAttribute; +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.loader.DirectorySource; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.registry.MetaDataRegistry; +import com.metaobjects.registry.MetaDataTypeProvider; +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.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * The docs view corpus ({@code fixtures/explorer-conformance/}, {@code docs/features/docs-view.md}): + * each fixture's project is loaded strictly, its committed optional inputs are read, and + * {@link DocsView} must reproduce the fixture's {@code expected.json} byte for byte, as the + * TypeScript reference does. A fixture's {@code provider.json} is applied before loading, every + * type it declares a plain node. + */ +public class DocsViewConformanceTest { + + /** A node of a type a fixture's provider.json declares: no behaviour beyond MetaData's own. */ + public static final class FixtureNode extends MetaData { + public FixtureNode(String type, String subType, String name) { + super(type, subType, name); + } + } + + public static Path corpus() { + for (Path p = Path.of("").toAbsolutePath(); p != null; p = p.getParent()) { + Path c = p.resolve("fixtures/explorer-conformance"); + if (Files.isDirectory(c)) return c; + } + throw new IllegalStateException("fixtures/explorer-conformance not found above " + Path.of("").toAbsolutePath()); + } + + public static List fixtures() 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; + } + + public static JsonElement readJson(Path dir, String name) throws IOException { + Path p = dir.resolve(name); + return Files.isRegularFile(p) ? JsonParser.parseString(Files.readString(p, StandardCharsets.UTF_8)) : null; + } + + /** A provider for a fixture's provider.json: every type a plain node, its attrs and child slots as declared. */ + static MetaDataTypeProvider fixtureProvider(JsonObject def) { + return new MetaDataTypeProvider() { + @Override public String getProviderId() { return def.get("provider").getAsString(); } + @Override public String[] getDependencies() { return new String[]{"core-types", "attribute-types", "object-types"}; } + @Override public String getDescription() { return "Test-only: a docs-view fixture's vocabulary."; } + @Override public void registerTypes(MetaDataRegistry registry) { + for (JsonElement t : def.getAsJsonArray("types")) { + JsonObject type = t.getAsJsonObject(); + registry.registerType(FixtureNode.class, b -> { + b.type(type.get("type").getAsString()).subType(type.get("subType").getAsString()) + .description(type.get("description").getAsString()); + slots(b, type.getAsJsonArray("children")); + }); + } + for (JsonElement e : def.getAsJsonArray("extends")) { + JsonObject ext = e.getAsJsonObject(); + assertEquals("metadata", ext.get("type").getAsString()); + registry.extendType(MetaRoot.class, b -> slots(b, ext.getAsJsonArray("children"))); + } + } + }; + } + + private static void slots(com.metaobjects.registry.TypeDefinitionBuilder b, JsonArray children) { + for (JsonElement c : children) { + JsonObject slot = c.getAsJsonObject(); + String type = slot.get("type").getAsString(); + String name = slot.get("name").getAsString(); + if (MetaAttribute.TYPE_ATTR.equals(type)) { + var a = slot.get("min").getAsInt() > 0 + ? b.requiredAttributeWithConstraints(name) : b.optionalAttributeWithConstraints(name); + var typed = a.ofType(StringAttribute.SUBTYPE_STRING); + if (slot.has("isArray") && slot.get("isArray").getAsBoolean()) typed.asArray(); + else typed.asSingle(); + } else { + b.optionalChild(type, slot.get("subType").getAsString(), name); + } + } + } + + /** A fixture's project, loaded strictly with its provider.json applied; other ports' suites reuse it. */ + public static MetaDataLoader load(String name) throws IOException { + Path dir = corpus().resolve(name); + JsonElement def = readJson(dir, "provider.json"); + LoaderOptions opts = LoaderOptions.create(false, false, true); + if (def != null) opts.setProviders(List.of(fixtureProvider(def.getAsJsonObject()))); + MetaDataLoader loader = new MetaDataLoader(opts, MetaDataLoader.SUBTYPE_MANUAL, "docs_view_" + name.replace('-', '_')); + loader.init(); + loader.load(new DirectorySource(dir.resolve("project/metaobjects"), new DirectorySource.Options()).expandToList()); + assertTrue(name + ": expected a clean strict load, got: " + loader.getErrors(), loader.getErrors().isEmpty()); + return loader; + } + + static JsonObject viewOf(String name) throws IOException { + Path dir = corpus().resolve(name); + return DocsView.build(load(name).getRoot(), readJson(dir, "verify.json"), readJson(dir, "hashes.json"), readJson(dir, "routes.json")); + } + + @Test + public void corpusHoldsTheFixturesTheReadmeDescribes() throws IOException { + assertEquals(List.of("crm", "model-alone", "shop"), fixtures()); + } + + @Test + public void everyFixtureReproducesExpectedJson() throws IOException { + List failures = new ArrayList<>(); + for (String name : fixtures()) { + String expected = Files.readString(corpus().resolve(name).resolve("expected.json"), StandardCharsets.UTF_8); + String actual = DocsView.serialize(viewOf(name)); + if (!expected.equals(actual)) { + String scratch = System.getenv("DOCS_VIEW_ACTUAL_DIR"); + if (scratch != null) Files.writeString(Path.of(scratch, name + ".json"), actual, StandardCharsets.UTF_8); + failures.add(name); + } + } + assertEquals("docs view differs from expected.json (set DOCS_VIEW_ACTUAL_DIR to write what this port builds)", + List.of(), failures); + } + + @Test + public void jsonWriterMatchesJavaScript() { + assertEquals("1.5", DocsViewJson.number(1.5)); + assertEquals("3", DocsViewJson.number(3.0)); + assertEquals("1e+21", DocsViewJson.number(1e21)); + assertEquals("100000000000000000000", DocsViewJson.number(1e20)); + assertEquals("0.000001", DocsViewJson.number(0.000001)); + assertEquals("1e-7", DocsViewJson.number(1e-7)); + assertEquals("-12.25", DocsViewJson.number(-12.25)); + assertEquals("\"a\\u0001<>&
\\ud800\"", DocsViewJson.quote("a\u0001<>&
\ud800")); + } +} diff --git a/server/java/metadata/src/test/java/com/metaobjects/io/json/MetaDocsEndpointTest.java b/server/java/metadata/src/test/java/com/metaobjects/io/json/MetaDocsEndpointTest.java new file mode 100644 index 0000000000..62a256f2ea --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/io/json/MetaDocsEndpointTest.java @@ -0,0 +1,76 @@ +package com.metaobjects.io.json; + +import com.metaobjects.MetaRoot; +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 static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * The {@code GET /_meta/docs} helpers ({@code docs/features/metadata-api.md}): the body is the + * model-alone docs view, the bytes {@code fixtures/explorer-conformance/model-alone/expected.json} + * holds every port to, and the tag is the one TypeScript's mount sends. + */ +public class MetaDocsEndpointTest { + + static Path modelAlone() { + for (Path p = Path.of("").toAbsolutePath(); p != null; p = p.getParent()) { + Path c = p.resolve("fixtures/explorer-conformance/model-alone"); + if (Files.isDirectory(c)) return c; + } + throw new IllegalStateException("fixtures/explorer-conformance/model-alone not found"); + } + + static MetaRoot load(Path dir) { + MetaDataLoader loader = new MetaDataLoader(LoaderOptions.create(false, false, true), + MetaDataLoader.SUBTYPE_MANUAL, "meta_docs_endpoint"); + loader.init(); + loader.load(new DirectorySource(dir.resolve("project/metaobjects"), new DirectorySource.Options()).expandToList()); + assertTrue("clean load expected, got: " + loader.getErrors(), loader.getErrors().isEmpty()); + return loader.getRoot(); + } + + @Test + public void routePathSitsBesideMeta() { + assertEquals("/_meta/docs", MetaEndpoint.META_DOCS_ROUTE_PATH); + } + + @Test + public void bodyIsTheModelAloneDocsView() throws IOException { + Path dir = modelAlone(); + String expected = Files.readString(dir.resolve("expected.json"), StandardCharsets.UTF_8); + MetaRoot root = load(dir); + assertEquals(expected, MetaEndpoint.metaDocsJson(root)); + MetaEndpoint.Docs docs = MetaEndpoint.docs(root); + assertEquals(expected, docs.body()); + assertEquals(MetaEndpoint.metaDocsEtag(expected), docs.etag()); + } + + @Test + public void etagIsTypeScriptsValue() { + // metaDocsEtag(...) in @metaobjectsdev/runtime-ts gives these for the same strings. + assertEquals("\"5-4f9f2cab\"", MetaEndpoint.metaDocsEtag("hello")); + assertEquals("\"0-811c9dc5\"", MetaEndpoint.metaDocsEtag("")); + assertEquals("\"7-0579d2da\"", MetaEndpoint.metaDocsEtag("héllo ✓")); + } + + @Test + public void ifNoneMatchNamesTheTagOrStar() { + String tag = "\"5-4f9f2cab\""; + assertTrue(MetaEndpoint.etagMatches(tag, tag)); + assertTrue(MetaEndpoint.etagMatches("\"x\", W/" + tag, tag)); + assertTrue(MetaEndpoint.etagMatches("*", tag)); + assertFalse(MetaEndpoint.etagMatches(null, tag)); + assertFalse(MetaEndpoint.etagMatches("", tag)); + assertFalse(MetaEndpoint.etagMatches("\"other\"", tag)); + } +} From a00a3eeb2be0932c2df1e41ba05bc20702065a34 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 02:42:01 -0500 Subject: [PATCH 06/13] fix(ci): clear stale unpacked workspace crates before the Rust publish dry-run cargo publish --workspace unpacks its overlay-registry dependencies into a per-checkout directory and never re-unpacks while the version is unchanged, so the self-hosted runner verified metaobjects-codegen against a metaobjects-1.3.0 unpacked before metamodel_docs existed. Main has been red on the rust lane since #670 for this reason; the crate itself packages correctly. --- changelog.d/rust-publish-stale-sources.md | 7 +++ scripts/ci-local.sh | 7 ++- scripts/rust-clear-stale-publish-sources.sh | 51 +++++++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 changelog.d/rust-publish-stale-sources.md create mode 100755 scripts/rust-clear-stale-publish-sources.sh diff --git a/changelog.d/rust-publish-stale-sources.md b/changelog.d/rust-publish-stale-sources.md new file mode 100644 index 0000000000..9a4aefcde2 --- /dev/null +++ b/changelog.d/rust-publish-stale-sources.md @@ -0,0 +1,7 @@ +- **CI: the Rust publish dry-run no longer verifies against stale source.** `cargo publish + --workspace` unpacks the crates it depends on from its temporary overlay registry into a + directory fixed per checkout, and never unpacks them again while the version is unchanged, so a + machine that had run the gate before a new module landed compiled the old `metaobjects-1.3.0` + and failed with "could not find `metamodel_docs`". The gate now first clears unpacked copies of + the workspace's own crates that differ from the tree + (`scripts/rust-clear-stale-publish-sources.sh`). diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index b2920c1b61..9cbba46275 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -983,9 +983,12 @@ gate_rust_example() { # The crates are publishable (ADR-0065 Amendment 3), so a change that would make `cargo publish` # refuse them fails here, not on the day somebody publishes: package all three, build each # from its packaged copy, and stop short of uploading. --allow-dirty because this checks the -# packaging, not the working tree; nothing is uploaded, ever, by this gate. +# packaging, not the working tree; nothing is uploaded, ever, by this gate. Stale unpacked +# copies of our own crates are cleared first: cargo reuses them for the same version and would +# verify against old source (scripts/rust-clear-stale-publish-sources.sh says how). gate_rust_publish_dry_run() { - cargo publish --dry-run --workspace --locked --allow-dirty + "$ROOT/scripts/rust-clear-stale-publish-sources.sh" "$PWD" \ + && cargo publish --dry-run --workspace --locked --allow-dirty } # Load time per phase and per validation pass on the 20x fitness model. Record only: # it prints a table and never fails on a number, so a slowdown is read in the log and diff --git a/scripts/rust-clear-stale-publish-sources.sh b/scripts/rust-clear-stale-publish-sources.sh new file mode 100755 index 0000000000..8804ba179e --- /dev/null +++ b/scripts/rust-clear-stale-publish-sources.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Remove stale unpacked copies of this workspace's own crates before `cargo publish --dry-run`. +# +# `cargo publish --workspace` verifies each crate against a temporary overlay registry +# (target/package/tmp-registry) and unpacks the crates it depends on into +# $CARGO_HOME/registry/src/-/-/. The hash is fixed for a given checkout +# path, and cargo never unpacks again once that directory holds `.cargo-ok`. While the version +# stays the same, the next dry run on that machine therefore compiles the OLD source of the +# dependency, not what it just packaged. On a self-hosted runner that is permanent: main went +# red after a new module landed in `metaobjects`, because `metaobjects-codegen`'s verify step +# compiled a `metaobjects-1.3.0` unpacked before that module existed. +# +# A copy is stale when any file the crate packages differs from (or is missing in) the copy. +# Only stale copies are removed; one matching the tree is left for whoever is using it. +# +# Usage: scripts/rust-clear-stale-publish-sources.sh [workspace-dir] (default server/rust) +set -euo pipefail + +ws="${1:-$(cd "$(dirname "$0")/.." && pwd)/server/rust}" +src_root="${CARGO_HOME:-$HOME/.cargo}/registry/src" +[ -d "$src_root" ] || exit 0 + +cd "$ws" +# name version crate-dir, one line per workspace member +members=$(cargo metadata --no-deps --format-version 1 --locked | python3 -c ' +import json, os, sys +for p in json.load(sys.stdin)["packages"]: + print(p["name"], p["version"], os.path.dirname(p["manifest_path"])) +') + +# Files cargo rewrites or synthesises when packaging; never compared. +generated_re='^(Cargo\.toml|Cargo\.toml\.orig|Cargo\.lock|\.cargo_vcs_info\.json)$' + +while read -r name version dir; do + [ -n "$name" ] || continue + files=$(cargo package --list --allow-dirty --locked -p "$name" 2>/dev/null) + # Overlay registries are the unnamed `-` directories; crates.io's are named. + for copy in "$src_root"/-*/"$name-$version"; do + [ -d "$copy" ] || continue + stale=0 + while IFS= read -r rel; do + [[ "$rel" =~ $generated_re ]] && continue + [ -f "$dir/$rel" ] || continue # copied in from outside the crate (a workspace LICENSE) + if ! cmp -s "$dir/$rel" "$copy/$rel"; then stale=1; break; fi + done <<< "$files" + if [ "$stale" -eq 1 ]; then + echo "removing stale unpacked $name-$version: $copy" + rm -rf "$copy" + fi + done +done <<< "$members" From 12a40143667a7476cd3ffd2f169fed39e9d7ae4d Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 02:57:20 -0500 Subject: [PATCH 07/13] fix(java): keep the explorer data scripts out of codegen-base's layout, and hold docs-site to the inert line The model and stamp scripts move beside the docs view serializer (com.metaobjects.docsview.ExplorerModelScript), so codegen-base types no line breaks (LayoutRatchetTest). The codegen-noop inert tests hold docs-site to the line TypeScript's rules-inert test draws: the explorer documents every node, so only its data payload may differ, and only by the new nodes and members. --- .../docs/explorer/ExplorerSite.java | 39 +---- .../generator/kotlin/ReportingInertTest.kt | 14 +- .../generator/kotlin/RulesInertTest.kt | 14 +- .../generator/spring/ReportingInertTest.java | 12 ++ .../generator/spring/RulesInertTest.java | 12 ++ .../docsview/ExplorerModelScript.java | 57 ++++++++ .../metaobjects/docsview/DocsSiteInert.java | 138 ++++++++++++++++++ 7 files changed, 251 insertions(+), 35 deletions(-) create mode 100644 server/java/metadata/src/main/java/com/metaobjects/docsview/ExplorerModelScript.java create mode 100644 server/java/metadata/src/test/java/com/metaobjects/docsview/DocsSiteInert.java diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/docs/explorer/ExplorerSite.java b/server/java/codegen-base/src/main/java/com/metaobjects/docs/explorer/ExplorerSite.java index 309dff21de..8081c70e2a 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/docs/explorer/ExplorerSite.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/docs/explorer/ExplorerSite.java @@ -3,7 +3,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.metaobjects.docsview.DocsView; -import com.metaobjects.docsview.DocsViewJson; +import com.metaobjects.docsview.ExplorerModelScript; import com.metaobjects.template.TemplateConstants; import java.io.IOException; @@ -12,9 +12,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -125,26 +122,18 @@ public static Map emit(Input in) { public record ModelScript(String script, String stamp) {} /** - * The app's data file: one script setting {@code window.MO_MODEL}. Its {@code stamp} is the - * first 16 hex digits of the SHA-256 of the model's compact JSON without the stamp, and the - * stamp file repeats it. The same shape and bytes as TypeScript's {@code explorerModelScript}. + * The app's data file: one script setting {@code window.MO_MODEL}, whose stamp the stamp file + * repeats ({@link ExplorerModelScript}, the same bytes as TypeScript's {@code explorerModelScript}). */ public static ModelScript modelScript(String title, String footer, Map texts, Map templates, JsonObject view) { - JsonObject rest = new JsonObject(); - rest.addProperty("title", title); - rest.addProperty("footer", footer == null ? "" : footer); - rest.add("texts", sortedStrings(texts)); - rest.add("templates", sortedStrings(templates)); - rest.add("view", view); - String json = DocsViewJson.compact(rest); - String stamp = sha256(json).substring(0, 16); - return new ModelScript("window.MO_MODEL = {\"stamp\":" + DocsViewJson.quote(stamp) + "," + json.substring(1) + ";\n", stamp); + ExplorerModelScript m = ExplorerModelScript.of(title, footer, texts, templates, view); + return new ModelScript(m.script(), m.stamp()); } /** The file the app polls. */ public static String stampScript(String stamp) { - return "window.MO_STAMP = " + DocsViewJson.quote(stamp) + ";\n"; + return ExplorerModelScript.stampScript(stamp); } /** @@ -183,22 +172,6 @@ public static Map readPromptTexts(JsonObject view, List di return out; } - private static JsonObject sortedStrings(Map m) { - JsonObject o = new JsonObject(); - for (Map.Entry e : new TreeMap<>(m == null ? Map.of() : m).entrySet()) { - o.addProperty(e.getKey(), e.getValue()); - } - return o; - } - - private static String sha256(String s) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException(e); - } - } - private static String readIfPresent(Path dir, String name) { if (dir == null) return null; Path p = dir.resolve(name); 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 44231cc291..2dc1fa0bbf 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 @@ -1,5 +1,6 @@ package com.metaobjects.generator.kotlin +import com.metaobjects.docsview.DocsSiteInert import com.metaobjects.generator.kotlin.apidocs.DocsPaths import com.metaobjects.generator.kotlin.apidocs.KotlinApiDocsRenderer import com.metaobjects.generator.kotlin.apidocs.KotlinApiModelBuilder @@ -118,7 +119,18 @@ class ReportingInertTest { */ // shared-model writes no code: it publishes the model's own metadata files, named by its args, // which a bare in-memory model does not have. Its bytes are gated by the shared-model corpus. - private val codeGenerators get() = GENERATOR_REGISTRY.values.filter { it.name != "api-docs" && it.name != "shared-model" } + // 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 + } + + @Test + fun `docs-site differs by exactly the new nodes`() { + // The explorer lists every node, so each report and each dimension, measure and segment is one more; nothing else moves. + val info = GENERATOR_REGISTRY.getValue(DocsSiteInert.GENERATOR) + val problems = DocsSiteInert.check(emit("without", listOf(info)), emit("with", listOf(info)), setOf("object", "dimension", "measure", "segment")) + assertTrue(problems.isEmpty(), problems.joinToString("\n")) + } /** What a generator may add for the with-model: one file of the view-backed report, from five generators. */ private fun allowedFor(info: GeneratorInfo): Set = STORE_TOTALS_FILES[info.name]?.split('|')?.toSet() ?: emptySet() diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt index ac8261bd70..5165f58c18 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/RulesInertTest.kt @@ -1,5 +1,6 @@ package com.metaobjects.generator.kotlin +import com.metaobjects.docsview.DocsSiteInert import com.metaobjects.generator.kotlin.apidocs.DocsPaths import com.metaobjects.generator.kotlin.apidocs.KotlinApiDocsRenderer import com.metaobjects.generator.kotlin.apidocs.KotlinApiModelBuilder @@ -89,7 +90,18 @@ class RulesInertTest { } // shared-model writes no code: it publishes the model's own metadata files, named by its args. - private val codeGenerators get() = GENERATOR_REGISTRY.values.filter { it.name != "api-docs" && it.name != "shared-model" } + // 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 + } + + @Test + fun `docs-site differs by exactly the new nodes`() { + // The explorer lists every node, so the declared API and each transition are one more; nothing else moves. + val info = GENERATOR_REGISTRY.getValue(DocsSiteInert.GENERATOR) + val problems = DocsSiteInert.check(emit("without", listOf(info)), emit("with", listOf(info)), setOf("api", "transition")) + assertTrue(problems.isEmpty(), problems.joinToString("\n")) + } @Test fun `the with-model really carries the vocabulary`() { 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 7004f606e1..3d4966c6cb 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 @@ -4,6 +4,7 @@ import com.metaobjects.generator.Generator; import com.metaobjects.generator.GeneratorRegistry; import com.metaobjects.generator.GeneratorRegistry.GeneratorInfo; +import com.metaobjects.docsview.DocsSiteInert; import com.metaobjects.generator.apidocs.ApiUnit; import com.metaobjects.generator.apidocs.DocsPaths; import com.metaobjects.generator.apidocs.JavaApiDocsRenderer; @@ -24,6 +25,7 @@ import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; +import java.util.Set; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; @@ -188,6 +190,8 @@ public void everyGeneratorEmitsTheSameFilesButTheServedReportsOwn() throws Excep List leaks = new ArrayList<>(); List seen = new ArrayList<>(); for (GeneratorInfo info : GeneratorRegistry.list().values()) { + // docs-site documents every node, so it is held to its own line, below. + if (DocsSiteInert.GENERATOR.equals(info.stableName())) continue; String extra = SERVED_REPORT_FILES.get(info.stableName()); if (extra != null) seen.add(info.stableName()); try { @@ -212,6 +216,14 @@ public void everyGeneratorEmitsTheSameFilesButTheServedReportsOwn() throws Excep new ArrayList<>(new java.util.TreeSet<>(SERVED_REPORT_FILES.keySet())), seen); } + @Test + public void docsSiteDiffersByExactlyTheNewNodes() throws Exception { + // The explorer lists every node, so each report and each dimension, measure and segment is one more; nothing else moves. + GeneratorInfo info = GeneratorRegistry.list().get(DocsSiteInert.GENERATOR); + List problems = DocsSiteInert.check(emit("without", List.of(info)), emit("with", List.of(info)), Set.of("object", "dimension", "measure", "segment")); + assertTrue(String.join("\n", problems), problems.isEmpty()); + } + @Test public void noGeneratorEmitsAnythingForASourcelessReport() throws Exception { for (GeneratorInfo info : GeneratorRegistry.list().values()) { diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java index 4747770ef7..08232b7972 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/RulesInertTest.java @@ -4,6 +4,7 @@ import com.metaobjects.generator.Generator; import com.metaobjects.generator.GeneratorRegistry; import com.metaobjects.generator.GeneratorRegistry.GeneratorInfo; +import com.metaobjects.docsview.DocsSiteInert; import com.metaobjects.generator.apidocs.ApiUnit; import com.metaobjects.generator.apidocs.DocsPaths; import com.metaobjects.generator.apidocs.JavaApiDocsRenderer; @@ -25,6 +26,7 @@ import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; +import java.util.Set; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; @@ -137,6 +139,8 @@ public void theWithModelReallyCarriesTheVocabulary() throws Exception { public void everyGeneratorEmitsTheSameFiles() throws Exception { List leaks = new ArrayList<>(); for (GeneratorInfo info : GeneratorRegistry.list().values()) { + // docs-site documents every node, so it is held to its own line, below. + if (DocsSiteInert.GENERATOR.equals(info.stableName())) continue; try { assertSame(info.stableName(), emit("without", List.of(info)), emit("with", List.of(info))); } catch (AssertionError e) { @@ -146,6 +150,14 @@ public void everyGeneratorEmitsTheSameFiles() throws Exception { assertTrue(String.join("\n", leaks), leaks.isEmpty()); } + @Test + public void docsSiteDiffersByExactlyTheNewNodes() throws Exception { + // The explorer lists every node, so the declared API and each transition are one more; nothing else moves. + GeneratorInfo info = GeneratorRegistry.list().get(DocsSiteInert.GENERATOR); + List problems = DocsSiteInert.check(emit("without", List.of(info)), emit("with", List.of(info)), Set.of("api", "transition")); + assertTrue(String.join("\n", problems), problems.isEmpty()); + } + @Test public void theModelAndWebTiersInOneRunEmitTheSameFiles() throws Exception { Map all = GeneratorRegistry.list(); diff --git a/server/java/metadata/src/main/java/com/metaobjects/docsview/ExplorerModelScript.java b/server/java/metadata/src/main/java/com/metaobjects/docsview/ExplorerModelScript.java new file mode 100644 index 0000000000..5dadec06ab --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/docsview/ExplorerModelScript.java @@ -0,0 +1,57 @@ +package com.metaobjects.docsview; + +import com.google.gson.JsonObject; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Map; +import java.util.TreeMap; + +/** + * The explorer app's two data scripts, serialized beside the docs view they carry: the same shape + * and bytes as TypeScript's {@code explorerModelScript} and {@code explorerStampScript} + * ({@code @metaobjectsdev/docs-site}). + * + * @param script {@code window.MO_MODEL = {...};} — the view, the prompt texts, the title, the + * footer and any owned templates + * @param stamp the first 16 hex digits of the SHA-256 of the model's compact JSON without the stamp + */ +public record ExplorerModelScript(String script, String stamp) { + + /** The model script for these inputs; texts and templates are written in key order. */ + public static ExplorerModelScript of(String title, String footer, Map texts, + Map templates, JsonObject view) { + JsonObject rest = new JsonObject(); + rest.addProperty("title", title); + rest.addProperty("footer", footer == null ? "" : footer); + rest.add("texts", sortedStrings(texts)); + rest.add("templates", sortedStrings(templates)); + rest.add("view", view); + String json = DocsViewJson.compact(rest); + String stamp = sha256(json).substring(0, 16); + return new ExplorerModelScript("window.MO_MODEL = {\"stamp\":" + DocsViewJson.quote(stamp) + "," + json.substring(1) + ";\n", stamp); + } + + /** The stamp file the open app polls: {@code window.MO_STAMP = "";}. */ + public static String stampScript(String stamp) { + return "window.MO_STAMP = " + DocsViewJson.quote(stamp) + ";\n"; + } + + private static JsonObject sortedStrings(Map m) { + JsonObject o = new JsonObject(); + for (Map.Entry e : new TreeMap<>(m == null ? Map.of() : m).entrySet()) { + o.addProperty(e.getKey(), e.getValue()); + } + return o; + } + + private static String sha256(String s) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/server/java/metadata/src/test/java/com/metaobjects/docsview/DocsSiteInert.java b/server/java/metadata/src/test/java/com/metaobjects/docsview/DocsSiteInert.java new file mode 100644 index 0000000000..ef890fbbb8 --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/docsview/DocsSiteInert.java @@ -0,0 +1,138 @@ +package com.metaobjects.docsview; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * The line the {@code docs-site} generator is held to by the codegen-noop inert tests (the same + * line TypeScript's {@code rules-inert.test.ts} draws). The explorer documents every node of the + * model, so a model that declares more vocabulary gets more nodes in the docs view. Nothing else + * may move: the app files are byte-identical, no node goes away, every new node is of a type the + * vocabulary declares (whole nodes, or members of a node both models have), and every node both + * models have keeps its claims and its references both ways, gaining one only from what is new. + * + *

    The Java and Kotlin rules and reporting inert tests all call {@link #check}.

    + */ +public final class DocsSiteInert { + + private DocsSiteInert() {} + + /** The stable name both JVM registries list the generator under. */ + public static final String GENERATOR = "docs-site"; + + /** The files that carry the docs view and so may differ: the view, its data script, its stamp. */ + public static final List PAYLOAD = List.of("explorer.json", "explorer-model.js", "explorer-stamp.js"); + + /** + * What breaks the line, one entry per problem; empty when it holds. + * + * @param without the generator's files for the model without the vocabulary, by relative path + * @param with the same for the model with it + * @param newTypes the types the added vocabulary may contribute, as nodes or members ({@code type}) + */ + public static List check(Map without, Map with, Set newTypes) { + List problems = new ArrayList<>(); + if (!without.keySet().equals(with.keySet())) { + problems.add("docs-site: emitted file set " + without.keySet() + " became " + with.keySet()); + return problems; + } + String viewPath = null; + for (String path : without.keySet()) { + if (path.endsWith("/" + PAYLOAD.get(0)) || path.equals(PAYLOAD.get(0))) viewPath = path; + if (PAYLOAD.stream().anyMatch(p -> path.equals(p) || path.endsWith("/" + p))) continue; + if (!without.get(path).equals(with.get(path))) problems.add("docs-site: " + path + " differs"); + } + if (viewPath == null) { + problems.add("docs-site: no explorer.json in " + without.keySet()); + return problems; + } + Map before = nodes(without.get(viewPath)); + Map after = nodes(with.get(viewPath)); + // What the vocabulary added: whole nodes, and members of nodes both models have. + Set added = new LinkedHashSet<>(); + for (String id : before.keySet()) if (!after.containsKey(id)) problems.add("docs-site: node " + id + " went away"); + for (Map.Entry e : after.entrySet()) { + JsonObject n0 = before.get(e.getKey()); + if (n0 == null) { + added.add(e.getKey()); + requireType(problems, "node " + e.getKey(), e.getValue(), newTypes); + continue; + } + Map m0 = members(n0); + Map m1 = members(e.getValue()); + for (String id : m0.keySet()) if (!m1.containsKey(id)) problems.add("docs-site: member " + id + " went away"); + for (Map.Entry m : m1.entrySet()) { + if (m0.containsKey(m.getKey())) continue; + added.add(m.getKey()); + requireType(problems, "member " + m.getKey(), m.getValue(), newTypes); + } + } + if (added.isEmpty()) problems.add("docs-site: the view gained no node or member, so the model pair proves nothing"); + for (Map.Entry e : before.entrySet()) { + JsonObject n1 = after.get(e.getKey()); + if (n1 == null) continue; + JsonObject n0 = e.getValue(); + if (!n0.get("claims").equals(n1.get("claims"))) problems.add("docs-site: node " + e.getKey() + " changed its claims"); + gainedOnlyFromAdded(problems, e.getKey(), "refs", n0, n1, added); + gainedOnlyFromAdded(problems, e.getKey(), "referencedBy", n0, n1, added); + } + return problems; + } + + private static void requireType(List problems, String what, JsonObject n, Set newTypes) { + String type = n.get("type").getAsString(); + if (!newTypes.contains(type)) problems.add("docs-site: new " + what + " is a " + type + ", not one of " + newTypes); + } + + /** + * {@code key}'s entries on {@code n1} keep every one {@code n0} had, and each new one comes + * from an added node ({@code from}) or an added member ({@code via}). + */ + private static void gainedOnlyFromAdded(List problems, String id, String key, JsonObject n0, JsonObject n1, + Set added) { + JsonArray was = n0.getAsJsonArray(key); + JsonArray is = n1.getAsJsonArray(key); + for (JsonElement r : was) if (!is.contains(r)) problems.add("docs-site: node " + id + " lost one of its " + key + ": " + r); + for (JsonElement r : is) { + if (was.contains(r)) continue; + JsonObject ref = r.getAsJsonObject(); + if (!(added.contains(linkId(ref.get("from"))) || added.contains(linkId(ref.get("via"))))) { + problems.add("docs-site: node " + id + " gained one of its " + key + " from nothing new: " + r); + } + } + } + + private static String linkId(JsonElement link) { + return link != null && link.isJsonObject() && link.getAsJsonObject().has("id") ? link.getAsJsonObject().get("id").getAsString() : null; + } + + /** Every member of a node, nested ones included, by id. */ + private static Map members(JsonObject n) { + Map out = new LinkedHashMap<>(); + if (!n.has("memberGroups")) return out; + for (JsonElement g : n.getAsJsonArray("memberGroups")) { + for (JsonElement m : g.getAsJsonObject().getAsJsonArray("members")) { + out.put(m.getAsJsonObject().get("id").getAsString(), m.getAsJsonObject()); + out.putAll(members(m.getAsJsonObject())); + } + } + return out; + } + + private static Map nodes(String view) { + Map out = new LinkedHashMap<>(); + for (JsonElement n : JsonParser.parseString(view).getAsJsonObject().getAsJsonArray("nodes")) { + out.put(n.getAsJsonObject().get("id").getAsString(), n.getAsJsonObject()); + } + return out; + } +} From 6ab836422c6b58adc54ced0d0909f1a9cf374f09 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 03:14:24 -0500 Subject: [PATCH 08/13] no-mistakes(review): apply reviewer inline fixes --- docs/CONFORMANCE.md | 2 +- docs/features/explorer-data.md | 4 ++-- docs/features/explorer-site.md | 3 ++- docs/ports/java.md | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 5bb859c3d4..b0c20a007c 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -916,7 +916,7 @@ 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. -**One port runs it:** TypeScript, in +**TypeScript runs it** in `server/typescript/packages/metadata/test/docs-view-conformance.test.ts` (the view) and `server/typescript/packages/cli/test/explorer-fixture.test.ts` (the committed `verify.json` files are what the gate writes today) and `server/typescript/packages/runtime-ts/test/meta-docs-route.test.ts` diff --git a/docs/features/explorer-data.md b/docs/features/explorer-data.md index 962f5c1dac..a653375d57 100644 --- a/docs/features/explorer-data.md +++ b/docs/features/explorer-data.md @@ -158,8 +158,8 @@ malformed leaves its part of the view empty. 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 the other ports.** TypeScript builds it today; the corpus is what the - other ports will be held to. +- **The docs view in C#, Python and Rust.** TypeScript, Java and Kotlin 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 91119b3a0c..2e4943476a 100644 --- a/docs/features/explorer-site.md +++ b/docs/features/explorer-site.md @@ -88,7 +88,8 @@ On the JVM, wire it like any other generator, with its own output directory: It writes `docs/generated/site/`. The JVM build has no requirement gate of its own, so without `verifyFile` the requirement tree shows each claim but no verdict. The generator is not told the -routes the Spring controllers mount, so no node lists its REST routes. The generated-file lists come +routes the Spring controllers mount, so no node lists its REST routes unless you name them in +`routesFile` (`[{ node, method, path }]`, `node` a resolution key). The generated-file lists come from the hash manifest, which a write run saves after every generator has run: they show the files the previous write run recorded. The other args are in [the Java port's generator table](../ports/java.md#generators). diff --git a/docs/ports/java.md b/docs/ports/java.md index e247378a95..374683517b 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -469,7 +469,7 @@ name in every port. | `api-docs` | `JavaApiDocsGenerator` | `metaobjects-codegen-spring` | The Java SDK api reference: one page per entity, value object, projection, served report and template, an index and `AGENT-API.md`, under `/`. A `` entry like any other, run by `metaobjects:generate` and checked by `metaobjects:verify`. Args: `outputDir` (required; give it generated files only, since `verify` compares the whole tree), `apiSubDir` (default `api/java`), `layout` (`flat`, the default, or `package`), `projectName` (the agent page's header label, default `project`) and `modelBaseUrl` (absolute base for the links to the model pages; with none set the pages carry no `Model / metadata` link, since nothing writes a page for it to point at). The `metaobjects:docs` goal was removed in 8.1.0 ([migration](../features/migrations/docs-are-generators.md#java-and-kotlin)). Ejectable: the copy takes the page IR, the builder, the renderer, the page paths and the page templates with it. | | `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. | -| `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 generated files the committed hash manifest records for it (`generatedBy`, `sourceNode`), as of the last write run. 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) and `genStateDir` (default `.metaobjects/.gen-state`). 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. | +| `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 generated files the committed hash manifest records for it (`generatedBy`, `sourceNode`), as of the last write run. 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`). 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. | | `json-schema` | `MetaDataFileJsonSchemaGenerator` | `metaobjects-codegen-base` | A JSON Schema that validates metadata files, built from the type registry (`outputDir`, `outputFilename`). Ejectable: the copy takes `MetaDataFileSchemaWriter` with it. | From b62af3491406672d4df4ac6c862c33f385784c6a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 03:24:26 -0500 Subject: [PATCH 09/13] no-mistakes(review): Build JVM docs-site file lists from the run's output --- changelog.d/explorer-jvm.md | 3 +- docs/features/explorer-site.md | 6 +- docs/ports/java.md | 2 +- docs/ports/kotlin.md | 2 +- .../generator/DocsSiteGenerator.java | 33 ++++++--- .../com/metaobjects/generator/Generator.java | 9 +++ .../generator/util/GeneratedFileWriter.java | 47 ++++++++++++ .../mojo/AbstractMetaDataMojo.java | 15 ++++ .../mojo/MetaDataGeneratorMojo.java | 7 +- .../metaobjects/mojo/MetaDataVerifyMojo.java | 40 ++++++++--- .../mojo/GeneratedProvenanceTest.java | 71 +++++++++++++++++++ 11 files changed, 204 insertions(+), 31 deletions(-) diff --git a/changelog.d/explorer-jvm.md b/changelog.d/explorer-jvm.md index d879739e07..ac5be66a75 100644 --- a/changelog.d/explorer-jvm.md +++ b/changelog.d/explorer-jvm.md @@ -3,7 +3,8 @@ every `fixtures/explorer-conformance/` case. A new `docs-site` generator (`com.metaobjects.generator.DocsSiteGenerator`, in both the Java and Kotlin registries) writes `explorer.json`, the explorer app, `explorer-model.js` and `explorer-stamp.js`; each object - lists the generated files the committed hash manifest records for it. Optional args name a + lists the files the same run generated for it (the run builds the site after every other + generator, so `metaobjects:verify` renders what `generate` wrote). Optional args name a `verify --format json` payload (`verifyFile`) and the routes (`routesFile`). The running application can serve the same view at `{apiPrefix}/_meta/docs`: `MetaEndpoint.docs(root)` builds it once and carries its ETag, and the host mounts it as it mounts `/_meta`. The static diff --git a/docs/features/explorer-site.md b/docs/features/explorer-site.md index 2e4943476a..fa4158e7aa 100644 --- a/docs/features/explorer-site.md +++ b/docs/features/explorer-site.md @@ -89,9 +89,9 @@ On the JVM, wire it like any other generator, with its own output directory: It writes `docs/generated/site/`. The JVM build has no requirement gate of its own, so without `verifyFile` the requirement tree shows each claim but no verdict. The generator is not told the routes the Spring controllers mount, so no node lists its REST routes unless you name them in -`routesFile` (`[{ node, method, path }]`, `node` a resolution key). The generated-file lists come -from the hash manifest, which a write run saves after every generator has run: they show the -files the previous write run recorded. The other args are in +`routesFile` (`[{ node, method, path }]`, `node` a resolution key). The generated-file lists are the +files the same run generated: the run builds the site after every other generator, so +`metaobjects:verify` renders the same lists the write run wrote. The other args are in [the Java port's generator table](../ports/java.md#generators). ### The live view diff --git a/docs/ports/java.md b/docs/ports/java.md index 374683517b..a5b0edd167 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -469,7 +469,7 @@ name in every port. | `api-docs` | `JavaApiDocsGenerator` | `metaobjects-codegen-spring` | The Java SDK api reference: one page per entity, value object, projection, served report and template, an index and `AGENT-API.md`, under `/`. A `` entry like any other, run by `metaobjects:generate` and checked by `metaobjects:verify`. Args: `outputDir` (required; give it generated files only, since `verify` compares the whole tree), `apiSubDir` (default `api/java`), `layout` (`flat`, the default, or `package`), `projectName` (the agent page's header label, default `project`) and `modelBaseUrl` (absolute base for the links to the model pages; with none set the pages carry no `Model / metadata` link, since nothing writes a page for it to point at). The `metaobjects:docs` goal was removed in 8.1.0 ([migration](../features/migrations/docs-are-generators.md#java-and-kotlin)). Ejectable: the copy takes the page IR, the builder, the renderer, the page paths and the page templates with it. | | `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. | -| `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 generated files the committed hash manifest records for it (`generatedBy`, `sourceNode`), as of the last write run. 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`). 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. | +| `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 the same run generated for it (`generatedBy`, `sourceNode`): the run builds the site after every other generator, 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. | | `json-schema` | `MetaDataFileJsonSchemaGenerator` | `metaobjects-codegen-base` | A JSON Schema that validates metadata files, built from the type registry (`outputDir`, `outputFilename`). Ejectable: the copy takes `MetaDataFileSchemaWriter` with it. | diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index b718a132de..6fbbab5aec 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -187,7 +187,7 @@ The 20 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): | `KotlinSharedModelGenerator` | `.metaobjects.json` and `metaobjects.pkg.json` — the FR-023 shared-model artifact and manifest a consumer's `meta deps sync` reads. See [Publishing a shared model](#publishing-a-shared-model-shared-model) | once per project (`include` selects the nodes) | | `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 | -| `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 the committed hash manifest. 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 | +| `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 the same run (built after every other generator). 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 project. Keep `` at plugin level and bind the goal in ``: without the diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java index 71a95b3f73..37c52fd256 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java @@ -5,6 +5,7 @@ import com.google.gson.JsonParser; import com.metaobjects.docs.explorer.ExplorerSite; import com.metaobjects.docsview.DocsView; +import com.metaobjects.generator.util.GeneratedFileWriter; import com.metaobjects.generator.util.HashManifest; import com.metaobjects.loader.MetaDataLoader; @@ -27,10 +28,12 @@ * write the same bytes. * *

    It builds the docs view from the model this run loaded ({@link DocsView#build}), lists the - * generated files the committed hash manifest records for each node ({@code generatedBy} and - * {@code sourceNode}), and writes the app, its data script, its stamp and {@code explorer.json} - * through {@link ExplorerSite}. The files it lists are the ones the last write run recorded: the - * manifest is saved after every generator has run.

    + * files this run generated for each node ({@code generatedBy} and {@code sourceNode}, from the open + * {@link GeneratedFileWriter.Run}), and writes the app, its data script, its stamp and + * {@code explorer.json} through {@link ExplorerSite}. The runner runs it after every other + * generator ({@link #readsRunOutput}), so a write run and {@code metaobjects:verify} list the same + * files. With no run open (a test or an embedder driving it alone) it lists what the hash manifest + * in {@code genStateDir} records.

    * *

    Args: {@code outputDir} (required); {@code subDir} (default {@code site}; empty writes at the * root); {@code title} (default: the project directory's name); {@code stamp} (footer text, default @@ -65,8 +68,8 @@ public class DocsSiteGenerator extends FileEmittingGenerator { /** * The owned theme, the prompts directory and the verify payload are read beside the model - * (ADR-0064): editing one regenerates. The hash manifest is not an input: it changes only - * when a run writes, and that run regenerates anyway. + * (ADR-0064): editing one regenerates. The hash manifest is not an input: the files the site + * lists are the ones this run generates, which follow from the model and these inputs. */ @Override public List extraInputs() { @@ -79,6 +82,11 @@ public List extraInputs() { return inputs; } + @Override + public boolean readsRunOutput() { + return true; + } + @Override protected List generate(MetaDataLoader loader) { Path project = Path.of(getArg(ARG_PROJECT_ROOT, System.getProperty("user.dir"))).toAbsolutePath().normalize(); @@ -88,7 +96,11 @@ protected List generate(MetaDataLoader loader) { JsonElement verify = hasArg(ARG_VERIFY_FILE) ? readJson(project.resolve(getArg(ARG_VERIFY_FILE))) : null; Path genState = project.resolve(getArg(ARG_GEN_STATE_DIR, DEFAULT_GEN_STATE_DIR)); JsonElement routes = hasArg(ARG_ROUTES_FILE) ? readJson(project.resolve(getArg(ARG_ROUTES_FILE))) : null; - JsonObject view = DocsView.build(loader.getRoot(), verify, manifest(genState), routes); + GeneratedFileWriter.Run run = GeneratedFileWriter.currentRun(); + Map runFiles = run == null ? null : run.generatedFiles(); + JsonObject generated = runFiles != null ? provenanceJson(runFiles) + : HashManifest.exists(genState) ? provenanceJson(HashManifest.loadProvenance(genState)) : null; + JsonObject view = DocsView.build(loader.getRoot(), verify, generated, routes); Path owned = project.resolve(OWNED_DOCS_SITE_DIR); Path assets = owned.resolve("assets"); @@ -105,11 +117,10 @@ view, title, getArg(ARG_STAMP, ""), return out; } - /** The manifest's provenance as the docs view reads it: {@code path → { generatedBy, sourceNode }}. */ - static JsonObject manifest(Path genStateDir) { - if (!HashManifest.exists(genStateDir)) return null; + /** Provenance as the docs view reads it: {@code path → { generatedBy, sourceNode }}. */ + private static JsonObject provenanceJson(Map provenance) { JsonObject out = new JsonObject(); - for (Map.Entry e : HashManifest.loadProvenance(genStateDir).entrySet()) { + for (Map.Entry e : provenance.entrySet()) { JsonObject entry = new JsonObject(); entry.addProperty("generatedBy", e.getValue().generatedBy()); if (e.getValue().sourceNode() != null) entry.addProperty("sourceNode", e.getValue().sourceNode()); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/Generator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/Generator.java index a6d2966b05..2c7afcf24a 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/Generator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/Generator.java @@ -32,4 +32,13 @@ default boolean cacheable() { default List extraInputs() { return List.of(); } + + /** + * Whether this generator reads the files the run generated + * ({@link com.metaobjects.generator.util.GeneratedFileWriter.Run#generatedFiles}). The runner + * runs every such generator after every other one, so it sees the whole run's output. + */ + default boolean readsRunOutput() { + return false; + } } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java index 9486106d97..984f2a0b84 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java @@ -179,9 +179,54 @@ public static final class Run implements AutoCloseable { // Non-null for a capture run (verify, ADR-0064 §4): every write lands here, keyed by the // normalized absolute path, and nothing is written to disk. private Map captured; + // This run's generated files, keyed as the manifest keys them, with the provenance each was + // recorded with: what the docs view lists. A capture run keys a rendered path by the real + // output directory it stands in for. + private final Map generated = new LinkedHashMap<>(); + private Map realDirByRendered = Map.of(); private Run() {} + /** + * The files this run has generated so far, {@code path → provenance}, keyed as the manifest + * keys them; {@code null} when the run has no project root to key them by. A narrowed run + * also lists what the committed manifest records ({@link #carryCommittedFiles}). + */ + public Map generatedFiles() { + return projectRoot == null ? null : Collections.unmodifiableMap(generated); + } + + /** List the committed manifest's files beside this run's, for a run that renders only some + * objects. Called by the runner after {@link #configureManifest}. */ + public Run carryCommittedFiles() { + if (provenance != null) generated.putAll(provenance); + return this; + } + + /** + * Key a capture run's files as the write run keys them: {@code projectRoot} is what keys + * are relative to, and {@code realDirByRendered} maps each directory the capture renders + * into to the output directory it stands in for. + */ + public Run keyCapturesAs(Path projectRoot, Map realDirByRendered) { + this.projectRoot = projectRoot; + this.realDirByRendered = realDirByRendered; + return this; + } + + private void noteCaptured(Path outFile) { + Path real = outFile.toAbsolutePath().normalize(); + for (Map.Entry e : realDirByRendered.entrySet()) { + Path rendered = e.getKey().toAbsolutePath().normalize(); + if (real.startsWith(rendered)) { + real = e.getValue().toAbsolutePath().normalize().resolve(rendered.relativize(real)); + break; + } + } + String key = OrphanSweep.keyFor(projectRoot, real); + if (key != null) generated.put(key, new HashManifest.Provenance(currentGeneratedBy, currentSourceNode)); + } + /** The bytes a capture run's generators emitted, by normalized absolute path; {@code null} * for an ordinary run. Read-only view. */ public Map captured() { @@ -265,6 +310,7 @@ private void record(String key, String hash) { // with no node, written by a generator the manifest names nothing for, stays plain. HashManifest.Provenance now = new HashManifest.Provenance(currentGeneratedBy, currentSourceNode); HashManifest.Provenance before = provenance.get(key); + generated.put(key, now); if (currentSourceNode != null) { if (!now.equals(provenance.put(key, now))) dirty = true; } else if (before != null && before.sourceNode() != null) { @@ -583,6 +629,7 @@ private static Outcome writeMarkerOnly(Path outFile, String content, Run run, bo return Outcome.REFUSED; } performWrite(outFile, content, run); + if (run != null && run.captured != null && run.projectRoot != null) run.noteCaptured(outFile); return Outcome.WRITTEN; } diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java index 60cef1daab..c0bc22dda1 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java @@ -841,6 +841,21 @@ private static GenFingerprint.Input config( String name, String value ) { } + /** The order a run executes {@code generators} in, as indices: declaration order, with every + * generator that reads the run's output ({@link Generator#readsRunOutput}) after every other. */ + static List runOrder(List generators) { + List order = new ArrayList<>(); + for (int i = 0; i < generators.size(); i++) if (!generators.get(i).readsRunOutput()) order.add(i); + for (int i = 0; i < generators.size(); i++) if (generators.get(i).readsRunOutput()) order.add(i); + return order; + } + + /** What the manifest's {@code generatedBy} names {@code gen}, declared by {@code param} ({@code null}: undeclared). */ + static String generatedBy(GeneratorParam param, Generator gen) { + return param != null && param.getClassname() != null + ? RequiresCheck.generatorName(param.getClassname()) : gen.getClass().getSimpleName(); + } + /** * Reflectively instantiate and configure each declared generator, mirroring the exact * mechanism {@code meta:gen} uses. This is the single source of truth for generator diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java index 8377e6681f..95ee41415a 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java @@ -155,6 +155,7 @@ protected void executeGenerators(MetaDataLoader loader, List generato if (genStateDir != null) { run.configureManifest(genStateDir, projectRoot); run.placeBy(placementOf(loader)); + if (selected != null) run.carryCommittedFiles(); } // Every output dir THIS EXECUTION's generators write to, with the handEdits @@ -166,16 +167,14 @@ protected void executeGenerators(MetaDataLoader loader, List generato Set runOwners = new HashSet<>(); List params = getGenerators(); - for (int i = 0; i < generatorImpls.size(); i++) { + for (int i : runOrder(generatorImpls)) { Generator gen = generatorImpls.get(i); getLog().info("MetaData Mojo > Executing Generator: " + gen.getClass().getName() ); GeneratorParam param = params != null && i < params.size() ? params.get(i) : null; String handEdits = param != null ? param.validatedHandEdits() : GeneratorParam.HAND_EDITS_KEEP; HashManifest.Owner owner = genStateDir != null && param != null ? ownerOf(param) : null; if (owner != null) runOwners.add(owner); - String generatedBy = param != null && param.getClassname() != null - ? RequiresCheck.generatorName(param.getClassname()) : gen.getClass().getSimpleName(); - run.attributeTo( gen.getClass().getSimpleName(), handEdits, owner, generatedBy ); + run.attributeTo( gen.getClass().getSimpleName(), handEdits, owner, generatedBy(param, gen) ); gen.execute( loader ); if (genStateDir != null && param != null) { diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java index c4fb0dd1d4..f7a68031cf 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java @@ -630,13 +630,7 @@ private void verifyCodegen() throws MojoExecutionException, MojoFailureException // Build + run generators with the temp-dir overrides applied. List generatorImpls = buildGenerators(projectClassLoader, overrides); try { - try (GeneratedFileWriter.Run capture = GeneratedFileWriter.beginCaptureRun()) { - for (Generator gen : generatorImpls) { - getLog().info("MetaData Verify Mojo > Regenerating (in memory): " + gen.getClass().getName()); - gen.execute(loader); - } - rendered = new HashMap<>(capture.captured()); - } + rendered = renderInMemory(loader, generatorImpls, targets, projectRoot, true); // Compare each output directory's temp tree against its committed tree. Map ownHashes = hashes == null ? null @@ -693,6 +687,32 @@ private void verifyCodegen() throws MojoExecutionException, MojoFailureException } } + /** + * Run {@code generatorImpls} as the generate goal does (the same order and attribution) through + * a capture run, and return what they rendered. Files are keyed by the committed output + * directory each render directory stands in for, so the docs site lists what generate lists. + */ + private Map renderInMemory(MetaDataLoader loader, List generatorImpls, + List targets, Path projectRoot, boolean announce) { + List params = getGenerators(); + try (GeneratedFileWriter.Run capture = GeneratedFileWriter.beginCaptureRun()) { + if (projectRoot != null) { + Map realDirByRendered = new LinkedHashMap<>(); + for (GenTarget t : targets) realDirByRendered.put(t.tempDir, t.realDir); + capture.keyCapturesAs(projectRoot, realDirByRendered); + } + for (int i : runOrder(generatorImpls)) { + Generator gen = generatorImpls.get(i); + if (announce) getLog().info("MetaData Verify Mojo > Regenerating (in memory): " + gen.getClass().getName()); + GeneratorParam param = params != null && i < params.size() ? params.get(i) : null; + capture.attributeTo(gen.getClass().getSimpleName(), GeneratorParam.HAND_EDITS_KEEP, null, + generatedBy(param, gen)); + gen.execute(loader); + } + return new HashMap<>(capture.captured()); + } + } + /** * ADR-0019 Amendment 2: the other {@code wire} setting under which the generators reproduce the * committed output exactly, or {@code null} when none does. Probes decimals {native, string} x @@ -713,9 +733,9 @@ private WireFormat matchingWire(MetaDataLoader loader, ClassLoader projectClassL for (WireFormat.Durations u : WireFormat.Durations.values()) { if (d == used.decimals() && n == usedNulls && u == used.durations()) continue; loader.getRoot().setWireFormat(new WireFormat(d, n, u)); - try (GeneratedFileWriter.Run capture = GeneratedFileWriter.beginCaptureRun()) { - for (Generator gen : buildGenerators(projectClassLoader, overrides)) gen.execute(loader); - rendered = new HashMap<>(capture.captured()); + try { + rendered = renderInMemory(loader, buildGenerators(projectClassLoader, overrides), + targets, projectRoot, false); } catch (RuntimeException e) { getLog().debug("MetaData Verify Mojo > wire probe failed: " + e); return null; diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java index 793eb1dfb1..83b5ce1c52 100644 --- a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java @@ -198,4 +198,75 @@ public void aSecondRunWritesNoManifestFile() throws Exception { assertEquals(p.toString(), 1_000_000_000_000L, Files.getLastModifiedTime(p).toMillis()); } } + + /** The node {@code acme::shop::Order}'s generated files in the explorer's data, {@code generatedBy → paths}. */ + private static JsonObject orderFiles(JsonElement e) { + if (e.isJsonObject()) { + JsonObject o = e.getAsJsonObject(); + if (o.has("files") && o.has("name") && "Order".equals(o.get("name").getAsString()) + && "acme::shop".equals(o.get("package").getAsString())) { + JsonObject out = new JsonObject(); + for (JsonElement g : o.getAsJsonArray("files")) { + out.add(g.getAsJsonObject().get("generatedBy").getAsString(), g.getAsJsonObject().get("paths")); + } + return out; + } + for (String k : o.keySet()) { + JsonObject found = orderFiles(o.get(k)); + if (found != null) return found; + } + } else if (e.isJsonArray()) { + for (JsonElement c : e.getAsJsonArray()) { + JsonObject found = orderFiles(c); + if (found != null) return found; + } + } + return null; + } + + @Test + public void theFirstRunWithDocsSiteListsWhatItWroteAndVerifyRendersTheSameSite() throws Exception { + MetaDataGeneratorMojo mojo = generate(); + // Declared first, so the run itself must hold it back until the files exist. + List gens = new ArrayList<>(); + gens.add(GeneratorParam.builder(com.metaobjects.generator.DocsSiteGenerator.class.getName()) + .withArg("outputDir", module.resolve("docs").toString()).withArg("title", "Shop").build()); + gens.addAll(mojo.getGenerators()); + mojo.setGenerators(gens); + assertFalse(Files.exists(module.resolve(".metaobjects/.gen-state/.hashes"))); + mojo.execute(); + + // The oracle is the hash manifest the same run saved: the Order files it records. + JsonObject expected = new JsonObject(); + for (String key : JsonParser.parseString(Files.readString( + module.resolve(".metaobjects/.gen-state/.hashes/acme.shop.json"))).getAsJsonObject().keySet()) { + JsonObject e = entry("acme.shop.json", key); + if (!e.has("sourceNode") || !"acme::shop::Order".equals(e.get("sourceNode").getAsString())) continue; + String by = e.get("generatedBy").getAsString(); + if (!expected.has(by)) expected.add(by, new com.google.gson.JsonArray()); + expected.getAsJsonArray(by).add(key); + } + assertTrue("the run records Order's files: " + expected, expected.size() >= 2); + JsonObject listed = orderFiles(JsonParser.parseString(Files.readString(module.resolve("docs/site/explorer.json")))); + assertEquals(expected.keySet(), listed.keySet()); + for (String by : expected.keySet()) { + TreeSet want = new TreeSet<>(); + expected.getAsJsonArray(by).forEach(p -> want.add(p.getAsString())); + TreeSet got = new TreeSet<>(); + listed.getAsJsonArray(by).forEach(p -> got.add(p.getAsString())); + assertEquals(by, want, got); + } + + // A full verify renders the site again, in memory, and finds it as committed. + MetaDataVerifyMojo verify = new MetaDataVerifyMojo(); + verify.project = mojo.project; + verify.setLoader(LoaderParam.builder("per-package") + .withClassname("com.metaobjects.loader.MetaDataLoader") + .withSourceDir(module.resolve("metaobjects").toString()) + .build()); + verify.setGenerators(gens); + verify.setGlobals(java.util.Collections.emptyMap()); + verify.setFull(true); + verify.execute(); + } } From bbd9057167d699ce7bafaacbe2ad65e47155576a Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 03:26:51 -0500 Subject: [PATCH 10/13] no-mistakes(review): apply reviewer inline fixes --- docs/features/explorer-site.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/features/explorer-site.md b/docs/features/explorer-site.md index fa4158e7aa..c0b17b47b1 100644 --- a/docs/features/explorer-site.md +++ b/docs/features/explorer-site.md @@ -71,7 +71,7 @@ same model and inputs: every port that builds the docs view is held to | Port | Generator | The app | Inputs it reads | |---|---|---|---| | 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 the committed hash manifest records per node, and a `verify --format json` payload when you name one (`verifyFile`) | +| Java | `com.metaobjects.generator.DocsSiteGenerator` (`mvn metaobjects:generate`), no Node | The app only | The model, the files the same run generated per node, 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 | | | From 7a75c99678d42ecfe6d4797bcee7a71e211030ae Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 03:31:25 -0500 Subject: [PATCH 11/13] no-mistakes(review): List other executions' files in the JVM docs site --- changelog.d/explorer-jvm.md | 5 +-- docs/features/explorer-site.md | 5 +-- docs/ports/java.md | 2 +- docs/ports/kotlin.md | 2 +- .../generator/DocsSiteGenerator.java | 5 +-- .../generator/util/GeneratedFileWriter.java | 13 ++++---- .../mojo/AbstractMetaDataMojo.java | 32 +++++++++++++++++++ .../mojo/MetaDataGeneratorMojo.java | 2 +- .../metaobjects/mojo/MetaDataVerifyMojo.java | 2 ++ .../mojo/GeneratedProvenanceTest.java | 28 ++++++++++++++-- 10 files changed, 79 insertions(+), 17 deletions(-) diff --git a/changelog.d/explorer-jvm.md b/changelog.d/explorer-jvm.md index ac5be66a75..374709d7da 100644 --- a/changelog.d/explorer-jvm.md +++ b/changelog.d/explorer-jvm.md @@ -3,8 +3,9 @@ every `fixtures/explorer-conformance/` case. A new `docs-site` generator (`com.metaobjects.generator.DocsSiteGenerator`, in both the Java and Kotlin registries) writes `explorer.json`, the explorer app, `explorer-model.js` and `explorer-stamp.js`; each object - lists the files the same run generated for it (the run builds the site after every other - generator, so `metaobjects:verify` renders what `generate` wrote). Optional args name a + lists the files generated for it: this execution's (it builds the site after every other + generator it runs) and the committed manifest's for the module's other executions, so + `metaobjects:verify` renders what `generate` wrote. Optional args name a `verify --format json` payload (`verifyFile`) and the routes (`routesFile`). The running application can serve the same view at `{apiPrefix}/_meta/docs`: `MetaEndpoint.docs(root)` builds it once and carries its ETag, and the host mounts it as it mounts `/_meta`. The static diff --git a/docs/features/explorer-site.md b/docs/features/explorer-site.md index c0b17b47b1..48c4990f82 100644 --- a/docs/features/explorer-site.md +++ b/docs/features/explorer-site.md @@ -71,7 +71,7 @@ same model and inputs: every port that builds the docs view is held to | Port | Generator | The app | Inputs it reads | |---|---|---|---| | 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 the same run generated per node, and a `verify --format json` payload when you name one (`verifyFile`) | +| 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 | | | @@ -90,7 +90,8 @@ It writes `docs/generated/site/`. The JVM build has no requirement gate of its o `verifyFile` the requirement tree shows each claim but no verdict. The generator is not told the routes the Spring controllers mount, so no node lists its REST routes unless you name them in `routesFile` (`[{ node, method, path }]`, `node` a resolution key). The generated-file lists are the -files the same run generated: the run builds the site after every other generator, so +files this execution generated, beside 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 same lists the write run wrote. The other args are in [the Java port's generator table](../ports/java.md#generators). diff --git a/docs/ports/java.md b/docs/ports/java.md index a5b0edd167..00045c54f2 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -469,7 +469,7 @@ name in every port. | `api-docs` | `JavaApiDocsGenerator` | `metaobjects-codegen-spring` | The Java SDK api reference: one page per entity, value object, projection, served report and template, an index and `AGENT-API.md`, under `/`. A `` entry like any other, run by `metaobjects:generate` and checked by `metaobjects:verify`. Args: `outputDir` (required; give it generated files only, since `verify` compares the whole tree), `apiSubDir` (default `api/java`), `layout` (`flat`, the default, or `package`), `projectName` (the agent page's header label, default `project`) and `modelBaseUrl` (absolute base for the links to the model pages; with none set the pages carry no `Model / metadata` link, since nothing writes a page for it to point at). The `metaobjects:docs` goal was removed in 8.1.0 ([migration](../features/migrations/docs-are-generators.md#java-and-kotlin)). Ejectable: the copy takes the page IR, the builder, the renderer, the page paths and the page templates with it. | | `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. | -| `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 the same run generated for it (`generatedBy`, `sourceNode`): the run builds the site after every other generator, 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. | +| `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. | | `json-schema` | `MetaDataFileJsonSchemaGenerator` | `metaobjects-codegen-base` | A JSON Schema that validates metadata files, built from the type registry (`outputDir`, `outputFilename`). Ejectable: the copy takes `MetaDataFileSchemaWriter` with it. | diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index 6fbbab5aec..bff8fd2c9b 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -187,7 +187,7 @@ The 20 generators registered in `codegen-kotlin` (`GeneratorRegistry.kt`): | `KotlinSharedModelGenerator` | `.metaobjects.json` and `metaobjects.pkg.json` — the FR-023 shared-model artifact and manifest a consumer's `meta deps sync` reads. See [Publishing a shared model](#publishing-a-shared-model-shared-model) | once per project (`include` selects the nodes) | | `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 | -| `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 the same run (built after every other generator). 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 | +| `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 project. Keep `` at plugin level and bind the goal in ``: without the diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java index 37c52fd256..5604bd919b 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java @@ -28,8 +28,9 @@ * write the same bytes. * *

    It builds the docs view from the model this run loaded ({@link DocsView#build}), lists the - * files this run generated for each node ({@code generatedBy} and {@code sourceNode}, from the open - * {@link GeneratedFileWriter.Run}), and writes the app, its data script, its stamp and + * files generated for each node ({@code generatedBy} and {@code sourceNode}, from the open + * {@link GeneratedFileWriter.Run}: this run's, and the committed ones the runner carried in for the + * module's other executions), and writes the app, its data script, its stamp and * {@code explorer.json} through {@link ExplorerSite}. The runner runs it after every other * generator ({@link #readsRunOutput}), so a write run and {@code metaobjects:verify} list the same * files. With no run open (a test or an embedder driving it alone) it lists what the hash manifest diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java index 984f2a0b84..826b32c3d2 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java @@ -189,17 +189,18 @@ private Run() {} /** * The files this run has generated so far, {@code path → provenance}, keyed as the manifest - * keys them; {@code null} when the run has no project root to key them by. A narrowed run - * also lists what the committed manifest records ({@link #carryCommittedFiles}). + * keys them, after the committed files the runner carried in ({@link #carryCommittedFiles}); + * {@code null} when the run has no project root to key them by. */ public Map generatedFiles() { return projectRoot == null ? null : Collections.unmodifiableMap(generated); } - /** List the committed manifest's files beside this run's, for a run that renders only some - * objects. Called by the runner after {@link #configureManifest}. */ - public Run carryCommittedFiles() { - if (provenance != null) generated.putAll(provenance); + /** List {@code committed} (manifest files another execution, or the objects a narrowed run + * does not render, account for) beside this run's. Called by the runner before any + * generator runs; a file this run records replaces its committed entry. */ + public Run carryCommittedFiles(Map committed) { + generated.putAll(committed); return this; } diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java index c0bc22dda1..953f9926c9 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java @@ -20,6 +20,7 @@ import com.metaobjects.generator.EmitsPhysicalNameConstants; import com.metaobjects.loader.MetaDataLoader; import com.metaobjects.generator.util.HashManifest; +import com.metaobjects.generator.util.OrphanSweep; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.execution.MavenSession; @@ -841,6 +842,37 @@ private static GenFingerprint.Input config( String name, String value ) { } + /** + * The committed files a run of this execution lists beside its own: every manifest entry its + * orphan sweep leaves alone ({@link OrphanSweep#isCandidate}), such as another execution's, or + * every entry when {@code narrowed}, since a narrowed run sweeps nothing. The generate and + * verify goals both read it, so they list the same files. + */ + protected Map committedFilesBeside(Path genStateDir, Path projectRoot, + boolean narrowed) { + Map provenance = HashManifest.loadProvenance(genStateDir); + if (narrowed) return provenance; + Map owners = HashManifest.loadOwners(genStateDir); + Set runOwners = new HashSet<>(); + List runDirs = new ArrayList<>(); + for (GeneratorParam g : getGenerators() != null ? getGenerators() : List.of()) { + HashManifest.Owner owner = ownerOf(g); + if (owner != null) runOwners.add(owner); + String dir = mergeAndOverwriteArgs(g).get(GeneratorBase.ARG_OUTPUTDIR); + if (dir != null) runDirs.add(Path.of(dir).toAbsolutePath().normalize()); + } + Path root = projectRoot.toAbsolutePath().normalize(); + Map out = new LinkedHashMap<>(); + for (Map.Entry e : provenance.entrySet()) { + Path file = root.resolve(e.getKey()).normalize(); + boolean inRunDir = runDirs.stream().anyMatch(file::startsWith); + if (!OrphanSweep.isCandidate(owners.get(e.getKey()), inRunDir, runOwners, this::configuredOwners)) { + out.put(e.getKey(), e.getValue()); + } + } + return out; + } + /** The order a run executes {@code generators} in, as indices: declaration order, with every * generator that reads the run's output ({@link Generator#readsRunOutput}) after every other. */ static List runOrder(List generators) { diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java index 95ee41415a..ad0212c462 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java @@ -155,7 +155,7 @@ protected void executeGenerators(MetaDataLoader loader, List generato if (genStateDir != null) { run.configureManifest(genStateDir, projectRoot); run.placeBy(placementOf(loader)); - if (selected != null) run.carryCommittedFiles(); + run.carryCommittedFiles(committedFilesBeside(genStateDir, projectRoot, selected != null)); } // Every output dir THIS EXECUTION's generators write to, with the handEdits diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java index f7a68031cf..37c8f467b8 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataVerifyMojo.java @@ -700,6 +700,8 @@ private Map renderInMemory(MetaDataLoader loader, List Map realDirByRendered = new LinkedHashMap<>(); for (GenTarget t : targets) realDirByRendered.put(t.tempDir, t.realDir); capture.keyCapturesAs(projectRoot, realDirByRendered); + capture.carryCommittedFiles(committedFilesBeside( + projectRoot.resolve(".metaobjects").resolve(".gen-state"), projectRoot, false)); } for (int i : runOrder(generatorImpls)) { Generator gen = generatorImpls.get(i); diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java index 83b5ce1c52..81fe90f34e 100644 --- a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GeneratedProvenanceTest.java @@ -237,6 +237,13 @@ public void theFirstRunWithDocsSiteListsWhatItWroteAndVerifyRendersTheSameSite() mojo.execute(); // The oracle is the hash manifest the same run saved: the Order files it records. + assertSiteListsOrderFilesTheManifestRecords(); + + // A full verify renders the site again, in memory, and finds it as committed. + verifyInFull(mojo.project, gens); + } + + private void assertSiteListsOrderFilesTheManifestRecords() throws Exception { JsonObject expected = new JsonObject(); for (String key : JsonParser.parseString(Files.readString( module.resolve(".metaobjects/.gen-state/.hashes/acme.shop.json"))).getAsJsonObject().keySet()) { @@ -256,10 +263,11 @@ public void theFirstRunWithDocsSiteListsWhatItWroteAndVerifyRendersTheSameSite() listed.getAsJsonArray(by).forEach(p -> got.add(p.getAsString())); assertEquals(by, want, got); } + } - // A full verify renders the site again, in memory, and finds it as committed. + private void verifyInFull(MavenProject project, List gens) throws Exception { MetaDataVerifyMojo verify = new MetaDataVerifyMojo(); - verify.project = mojo.project; + verify.project = project; verify.setLoader(LoaderParam.builder("per-package") .withClassname("com.metaobjects.loader.MetaDataLoader") .withSourceDir(module.resolve("metaobjects").toString()) @@ -269,4 +277,20 @@ public void theFirstRunWithDocsSiteListsWhatItWroteAndVerifyRendersTheSameSite() verify.setFull(true); verify.execute(); } + + @Test + public void aDocsSiteExecutionOfItsOwnListsTheFilesAnotherExecutionGenerated() throws Exception { + generate().execute(); + + // A second execution of the module, sharing its manifest, runs docs-site alone. + MetaDataGeneratorMojo docs = generate(); + List gens = new ArrayList<>(List.of( + GeneratorParam.builder(com.metaobjects.generator.DocsSiteGenerator.class.getName()) + .withArg("outputDir", module.resolve("docs").toString()).withArg("title", "Shop").build())); + docs.setGenerators(gens); + docs.execute(); + + assertSiteListsOrderFilesTheManifestRecords(); + verifyInFull(docs.project, gens); + } } From 5f3879ee98fb6f61f955a692748a0b8bbbe9c4c5 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 03:35:52 -0500 Subject: [PATCH 12/13] no-mistakes(review): Re-run skip when manifest loses a file --- .../generator/DocsSiteGenerator.java | 5 +- .../mojo/AbstractMetaDataMojo.java | 8 +- .../metaobjects/mojo/DocsSiteSkipTest.java | 201 ++++++++++++++++++ 3 files changed, 209 insertions(+), 5 deletions(-) create mode 100644 server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DocsSiteSkipTest.java diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java index 5604bd919b..245cea56d2 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/DocsSiteGenerator.java @@ -69,8 +69,9 @@ public class DocsSiteGenerator extends FileEmittingGenerator { /** * The owned theme, the prompts directory and the verify payload are read beside the model - * (ADR-0064): editing one regenerates. The hash manifest is not an input: the files the site - * lists are the ones this run generates, which follow from the model and these inputs. + * (ADR-0064): editing one regenerates. The hash manifest is not an input here: 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. */ @Override public List extraInputs() { diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java index 953f9926c9..4b86901bd9 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java @@ -620,8 +620,8 @@ protected boolean fingerprintAnswersNoDrift(MetaDataLoader loader) { } /** - * Whether the stored fingerprint matches the one just computed and the files the last run - * wrote are all still there. With {@code checkHashes}, each file the manifest records must + * Whether the stored fingerprint matches the one just computed and the manifest records + * exactly the files the last run left, each still on disk as it left it. With {@code checkHashes}, each file the manifest records must * also still hash to its record (what a local {@code verify} needs). */ protected boolean fingerprintMatches(Path genStateDir, boolean checkHashes) { @@ -633,10 +633,12 @@ protected boolean fingerprintMatches(Path genStateDir, boolean checkHashes) { all.addAll(extraInputsOf(stored.get().extras())); if ( !GenFingerprint.fold(all).equals(stored.get().key()) ) return false; Path root = project.getBasedir().toPath(); + Map manifest = HashManifest.load(genStateDir); + if ( !manifest.keySet().equals(stored.get().outputs().keySet()) ) return false; // Amendment A: every recorded file must still hash to what the last run left on // disk. A hand edit therefore makes gen render, and a hand edit that gen merged and // kept does not. Verify also wants each file to match the manifest record. - for ( Map.Entry e : HashManifest.load(genStateDir).entrySet() ) { + for ( Map.Entry e : manifest.entrySet() ) { Path file = root.resolve(e.getKey()); if ( !Files.isRegularFile(file) ) return false; String onDisk = HashManifest.contentHash(Files.readString(file, StandardCharsets.UTF_8)); diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DocsSiteSkipTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DocsSiteSkipTest.java new file mode 100644 index 0000000000..c6991f6261 --- /dev/null +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DocsSiteSkipTest.java @@ -0,0 +1,201 @@ +package com.metaobjects.mojo; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.generator.DocsSiteGenerator; +import com.metaobjects.generator.direct.object.javacode.JavaObjectCodeGenerator; +import com.metaobjects.generator.spring.SpringDtoGenerator; +import com.metaobjects.generator.spring.SpringValueObjectGenerator; +import com.metaobjects.generator.util.HashManifest; +import org.apache.maven.project.MavenProject; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * ADR-0064 and the docs site: the site lists the files the module's other executions recorded in + * the shared hash manifest, so an unchanged build skips it, and a build in which another execution + * stops generating files runs it again and drops those files from the site. + */ +public class DocsSiteSkipTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + private Path module; + private Path engine; + private boolean skipped; + // Every execution the module configures, as the orphan sweep reads the POM. + private final List> executions = new ArrayList<>(); + + @Before + public void setUp() throws Exception { + module = tmp.getRoot().toPath().resolve("module"); + engine = tmp.newFolder("engine").toPath(); + Files.writeString(engine.resolve("engine.class"), "v1"); + Files.createDirectories(module.resolve("metaobjects")); + Files.writeString(module.resolve("metaobjects/meta.shop.json"), """ + {"metadata.root": {"package": "acme::shop", "children": [ + {"object.entity": {"name": "Order", "children": [ {"field.long": {"name": "id"}} ]}} + ]}} + """); + } + + private GeneratorParam entity() { + return GeneratorParam.builder(JavaObjectCodeGenerator.class.getName()) + .withArg("outputDir", "generated").withArg("type", "class").withArg("flavor", "pojoAware").build(); + } + + private List dto() { + return List.of( + GeneratorParam.builder(SpringValueObjectGenerator.class.getName()).withArg("outputDir", "generated-dto").build(), + GeneratorParam.builder(SpringDtoGenerator.class.getName()).withArg("outputDir", "generated-dto").build()); + } + + private static List list(Object... items) { + List out = new ArrayList<>(); + for (Object item : items) { + if (item instanceof GeneratorParam g) out.add(g); + else for (Object g : (List) item) out.add((GeneratorParam) g); + } + return out; + } + + private GeneratorParam docsSite() { + return GeneratorParam.builder(DocsSiteGenerator.class.getName()) + .withArg("outputDir", "docs").withArg("title", "Shop").build(); + } + + /** Run {@code generate} with {@code gens}; whether it skipped is left in {@link #skipped}. */ + private void generate(List gens) throws Exception { + skipped = false; + MetaDataGeneratorMojo mojo = new MetaDataGeneratorMojo() { + @Override + protected List engineClasspath() { + return List.of(engine); + } + + @Override + protected void onWholeRunSkipped() { + skipped = true; + super.onWholeRunSkipped(); + } + + @Override + protected Set configuredOwners() { + Set owners = new HashSet<>(); + for (List execution : executions) { + for (GeneratorParam g : execution) owners.add(ownerOf(g)); + } + return owners; + } + }; + MavenProject project = Mockito.mock(MavenProject.class); + Mockito.when(project.getBasedir()).thenReturn(module.toFile()); + mojo.project = project; + mojo.setLoader(LoaderParam.builder("docs-skip") + .withClassname("com.metaobjects.loader.MetaDataLoader") + .withSourceDir(module.resolve("metaobjects").toString()) + .build()); + mojo.setGenerators(new ArrayList<>(gens)); + mojo.setGlobals(Collections.emptyMap()); + mojo.execute(); + } + + /** The {@code generatedBy} names the site lists files under for {@code Order}. */ + private Set orderFilesListedBy() throws Exception { + JsonObject found = find(JsonParser.parseString(Files.readString(module.resolve("docs/site/explorer.json")))); + assertTrue("explorer.json has the Order node", found != null); + Set by = new HashSet<>(); + for (JsonElement g : found.getAsJsonArray("files")) by.add(g.getAsJsonObject().get("generatedBy").getAsString()); + return by; + } + + private static JsonObject find(JsonElement e) { + if (e.isJsonObject()) { + JsonObject o = e.getAsJsonObject(); + if (o.has("files") && o.has("name") && "Order".equals(o.get("name").getAsString())) return o; + for (String k : o.keySet()) { + JsonObject f = find(o.get(k)); + if (f != null) return f; + } + } else if (e.isJsonArray()) { + for (JsonElement c : e.getAsJsonArray()) { + JsonObject f = find(c); + if (f != null) return f; + } + } + return null; + } + + @Test + public void anUnchangedSecondRunWithDocsSiteSkips() throws Exception { + List all = list(docsSite(), entity(), dto()); + executions.add(all); + generate(all); + assertFalse(skipped); + generate(all); + assertTrue("nothing changed: the second run skips", skipped); + } + + @Test + public void twoExecutionsSharingTheManifestSettleAndSkip() throws Exception { + List a = list(entity(), dto()); + List b = List.of(docsSite()); + executions.add(a); + executions.add(b); + generate(a); + generate(b); + assertTrue(orderFilesListedBy().contains("dto")); + + // A's first fingerprint predates B's files, so A runs once more; B's does not. + generate(a); + generate(b); + assertTrue("the docs-site execution skips an unchanged build", skipped); + + generate(a); + assertTrue("the generating execution skips once settled", skipped); + generate(b); + assertTrue("the docs-site execution still skips", skipped); + } + + @Test + public void aGeneratorAnotherExecutionDropsLeavesTheSite() throws Exception { + List a = list(entity(), dto()); + List b = List.of(docsSite()); + executions.add(a); + executions.add(b); + for (int i = 0; i < 2; i++) { + generate(a); + generate(b); + } + assertTrue(skipped); + assertTrue(orderFilesListedBy().contains("dto")); + + // The module stops configuring the DTO generators: A sweeps their files and records. + a.subList(1, a.size()).clear(); + generate(a); + assertFalse(skipped); + assertFalse("the DTO files are swept", HashManifest.load(module.resolve(".metaobjects/.gen-state")) + .keySet().stream().anyMatch(k -> k.startsWith("generated-dto/"))); + + generate(b); + assertFalse("the manifest lost files the site lists: the docs-site execution runs", skipped); + assertFalse("the site no longer lists the DTO files", orderFilesListedBy().contains("dto")); + assertTrue(orderFilesListedBy().contains("entity")); + } +} From e6977b70e880acf6c2d657a00257d5b2bff27b24 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 28 Nov 2026 03:45:58 -0500 Subject: [PATCH 13/13] no-mistakes(document): Stale docs-view claim fixed; Java/Kotlin now build explorer.json --- docs/features/docs-view.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/features/docs-view.md b/docs/features/docs-view.md index 32f6202a74..dde6a53ae1 100644 --- a/docs/features/docs-view.md +++ b/docs/features/docs-view.md @@ -12,10 +12,12 @@ logic-less template such as Mustache can render it unaided. Every port that buil 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. `buildDocsView` and `serializeDocsView` are exported from -`@metaobjectsdev/metadata`, and `docsSiteFile()` writes the result as the site's -`explorer.json` (see [explorer-site.md](explorer-site.md)). The other ports build it as their -own step of the same plan. The explorer pages still render their HTML in TypeScript. +TypeScript builds it today, and so do Java and Kotlin (one JVM builder, `DocsView` in +`metadata`). `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 +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`. 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 @@ -268,7 +270,8 @@ Named node sets a map view opens on, all derived, each `{ id, kind, anchor, node `expected.json` is the view of its project and committed inputs, byte for byte. `server/typescript/packages/metadata/test/docs-view-conformance.test.ts` runs it, and also checks inheritance, references, the requirement list, custom vocabulary and a build without - the optional inputs. + the optional inputs. The JVM runs the same cases in `metadata`'s `DocsViewConformanceTest` and + Kotlin in `KotlinDocsSiteConformanceTest` ([CONFORMANCE.md](../CONFORMANCE.md)). - `server/typescript/packages/cli/test/explorer-fixture.test.ts`: the committed `verify.json` files are what the gate writes today, and a fresh verify payload builds the committed `shop/expected.json`.