From 2bdc2289124ef0bfc8cb73a6ac77fd6ca28523e0 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 27 Nov 2026 19:43:15 -0500 Subject: [PATCH 1/4] 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 2/4] 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 3/4] 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 4/4] 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.