@kensnzk/koyu 0.16.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +12 -8
- package/README.md +13 -10
- package/dist/analysis/contracts.d.ts +217 -0
- package/dist/analysis/contracts.d.ts.map +1 -0
- package/dist/analysis/contracts.js +27 -0
- package/dist/analysis/contracts.js.map +1 -0
- package/dist/analysis/index.d.ts +5 -0
- package/dist/analysis/index.d.ts.map +1 -0
- package/dist/analysis/index.js +17 -0
- package/dist/analysis/index.js.map +1 -0
- package/dist/analysis/json.d.ts +21 -0
- package/dist/analysis/json.d.ts.map +1 -0
- package/dist/analysis/json.js +111 -0
- package/dist/analysis/json.js.map +1 -0
- package/dist/cli.js +106 -35
- package/dist/cli.js.map +1 -1
- package/dist/core/derive.d.ts +13 -8
- package/dist/core/derive.d.ts.map +1 -1
- package/dist/core/derive.js +19 -13
- package/dist/core/derive.js.map +1 -1
- package/dist/core/diagnose.d.ts +4 -3
- package/dist/core/diagnose.d.ts.map +1 -1
- package/dist/core/diagnose.js +46 -11
- package/dist/core/diagnose.js.map +1 -1
- package/dist/core/diff.d.ts +3 -2
- package/dist/core/diff.d.ts.map +1 -1
- package/dist/core/diff.js +8 -5
- package/dist/core/diff.js.map +1 -1
- package/dist/core/fabric.d.ts +1 -3
- package/dist/core/fabric.d.ts.map +1 -1
- package/dist/core/fabric.js +8 -8
- package/dist/core/fabric.js.map +1 -1
- package/dist/core/graph.d.ts +2 -2
- package/dist/core/graph.d.ts.map +1 -1
- package/dist/core/graph.js +12 -5
- package/dist/core/graph.js.map +1 -1
- package/dist/core/light.d.ts.map +1 -1
- package/dist/core/light.js +2 -2
- package/dist/core/light.js.map +1 -1
- package/dist/core/model.d.ts +59 -10
- package/dist/core/model.d.ts.map +1 -1
- package/dist/core/model.js +128 -26
- package/dist/core/model.js.map +1 -1
- package/dist/core/parse.d.ts.map +1 -1
- package/dist/core/parse.js +83 -82
- package/dist/core/parse.js.map +1 -1
- package/dist/core/poly.d.ts +0 -4
- package/dist/core/poly.d.ts.map +1 -1
- package/dist/core/poly.js +1 -5
- package/dist/core/poly.js.map +1 -1
- package/dist/core/site.d.ts +9 -0
- package/dist/core/site.d.ts.map +1 -1
- package/dist/core/site.js +8 -2
- package/dist/core/site.js.map +1 -1
- package/dist/core/tolerance.d.ts +1 -1
- package/dist/core/tolerance.js +2 -2
- package/dist/core/tolerance.js.map +1 -1
- package/dist/core/vertical.d.ts +9 -2
- package/dist/core/vertical.d.ts.map +1 -1
- package/dist/core/vertical.js +8 -1
- package/dist/core/vertical.js.map +1 -1
- package/dist/core/vocabulary.d.ts.map +1 -1
- package/dist/core/vocabulary.js +17 -5
- package/dist/core/vocabulary.js.map +1 -1
- package/dist/diagnostics.d.ts +2 -0
- package/dist/diagnostics.d.ts.map +1 -0
- package/dist/diagnostics.js +3 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/diff.d.ts +2 -0
- package/dist/diff.d.ts.map +1 -0
- package/dist/diff.js +3 -0
- package/dist/diff.js.map +1 -0
- package/dist/draw/index.js +1 -1
- package/dist/draw/index.js.map +1 -1
- package/dist/draw/plan.js +5 -5
- package/dist/draw/plan.js.map +1 -1
- package/dist/form.d.ts +5 -0
- package/dist/form.d.ts.map +1 -0
- package/dist/form.js +4 -0
- package/dist/form.js.map +1 -0
- package/dist/graph.d.ts +2 -0
- package/dist/graph.d.ts.map +1 -0
- package/dist/graph.js +3 -0
- package/dist/graph.js.map +1 -0
- package/dist/index.d.ts +2 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +36 -45
- package/dist/index.js.map +1 -1
- package/dist/mcp.js +81 -30
- package/dist/mcp.js.map +1 -1
- package/dist/model.d.ts +3 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +3 -0
- package/dist/model.js.map +1 -0
- package/dist/parse-file.d.ts.map +1 -1
- package/dist/parse-file.js +18 -3
- package/dist/parse-file.js.map +1 -1
- package/dist/validate/assessment.d.ts +8 -0
- package/dist/validate/assessment.d.ts.map +1 -0
- package/dist/validate/assessment.js +1738 -0
- package/dist/validate/assessment.js.map +1 -0
- package/dist/validate/builtin/access.d.ts +55 -0
- package/dist/validate/builtin/access.d.ts.map +1 -0
- package/dist/validate/builtin/access.js +494 -0
- package/dist/validate/builtin/access.js.map +1 -0
- package/dist/validate/builtin/daylight.d.ts +44 -0
- package/dist/validate/builtin/daylight.d.ts.map +1 -0
- package/dist/validate/builtin/daylight.js +233 -0
- package/dist/validate/builtin/daylight.js.map +1 -0
- package/dist/validate/builtin/door-column-collisions.d.ts +47 -0
- package/dist/validate/builtin/door-column-collisions.d.ts.map +1 -0
- package/dist/validate/builtin/door-column-collisions.js +189 -0
- package/dist/validate/builtin/door-column-collisions.js.map +1 -0
- package/dist/validate/builtin/envelope.d.ts +30 -0
- package/dist/validate/builtin/envelope.d.ts.map +1 -0
- package/dist/validate/builtin/envelope.js +169 -0
- package/dist/validate/builtin/envelope.js.map +1 -0
- package/dist/validate/builtin/freeze.d.ts +3 -0
- package/dist/validate/builtin/freeze.d.ts.map +1 -0
- package/dist/validate/builtin/freeze.js +21 -0
- package/dist/validate/builtin/freeze.js.map +1 -0
- package/dist/validate/builtin/index.d.ts +38 -0
- package/dist/validate/builtin/index.d.ts.map +1 -0
- package/dist/validate/builtin/index.js +106 -0
- package/dist/validate/builtin/index.js.map +1 -0
- package/dist/validate/builtin/site.d.ts +62 -0
- package/dist/validate/builtin/site.d.ts.map +1 -0
- package/dist/validate/builtin/site.js +333 -0
- package/dist/validate/builtin/site.js.map +1 -0
- package/dist/validate/builtin/vertical-runs.d.ts +53 -0
- package/dist/validate/builtin/vertical-runs.d.ts.map +1 -0
- package/dist/validate/builtin/vertical-runs.js +290 -0
- package/dist/validate/builtin/vertical-runs.js.map +1 -0
- package/dist/validate/contracts.d.ts +188 -0
- package/dist/validate/contracts.d.ts.map +1 -0
- package/dist/validate/contracts.js +28 -0
- package/dist/validate/contracts.js.map +1 -0
- package/dist/validate/index.d.ts +2 -59
- package/dist/validate/index.d.ts.map +1 -1
- package/dist/validate/index.js +22 -70
- package/dist/validate/index.js.map +1 -1
- package/dist/vocabulary.d.ts +2 -0
- package/dist/vocabulary.d.ts.map +1 -0
- package/dist/vocabulary.js +3 -0
- package/dist/vocabulary.js.map +1 -0
- package/editors/vscode/syntaxes/koyu.tmLanguage.json +2 -2
- package/examples/basement/main.muro +3 -3
- package/examples/complex/main.muro +1 -1
- package/examples/complex/podium.muro +1 -1
- package/examples/complex/site.muro +6 -6
- package/examples/house/L2.muro +1 -1
- package/examples/house/main.muro +1 -1
- package/examples/house/site.muro +4 -4
- package/examples/house.muro +6 -6
- package/examples/mansion.muro +2 -2
- package/examples/office.muro +3 -3
- package/examples/steps/04-exterior.muro +1 -1
- package/examples/steps/05-two-storeys.muro +1 -1
- package/examples/steps/06-finished.muro +2 -2
- package/examples/tower/L2.muro +1 -1
- package/examples/tower/main.muro +1 -1
- package/examples/tower/site.muro +4 -4
- package/examples/twin/main.muro +1 -1
- package/examples/twin/podium.muro +4 -4
- package/examples/twin/site.muro +8 -8
- package/examples/two-rooms.canonical.json +4 -4
- package/examples/two-rooms.muro +2 -2
- package/package.json +41 -9
- package/src/analysis/contracts.ts +234 -0
- package/src/analysis/index.ts +61 -0
- package/src/analysis/json.ts +117 -0
- package/src/cli.ts +116 -36
- package/src/core/derive.ts +32 -15
- package/src/core/diagnose.ts +63 -16
- package/src/core/diff.ts +10 -6
- package/src/core/fabric.ts +18 -9
- package/src/core/graph.ts +19 -5
- package/src/core/light.ts +2 -2
- package/src/core/model.ts +141 -31
- package/src/core/parse.ts +100 -85
- package/src/core/poly.ts +1 -8
- package/src/core/site.ts +19 -2
- package/src/core/tolerance.ts +2 -2
- package/src/core/vertical.ts +10 -3
- package/src/core/vocabulary.ts +18 -5
- package/src/diagnostics.ts +8 -0
- package/src/diff.ts +14 -0
- package/src/draw/index.ts +1 -1
- package/src/draw/plan.ts +5 -5
- package/src/form.ts +37 -0
- package/src/graph.ts +12 -0
- package/src/index.ts +40 -175
- package/src/mcp.ts +85 -35
- package/src/model.ts +43 -0
- package/src/parse-file.ts +17 -3
- package/src/validate/assessment.ts +1934 -0
- package/src/validate/builtin/access.ts +642 -0
- package/src/validate/builtin/daylight.ts +321 -0
- package/src/validate/builtin/door-column-collisions.ts +266 -0
- package/src/validate/builtin/envelope.ts +227 -0
- package/src/validate/builtin/freeze.ts +19 -0
- package/src/validate/builtin/index.ts +156 -0
- package/src/validate/builtin/site.ts +445 -0
- package/src/validate/builtin/vertical-runs.ts +390 -0
- package/src/validate/contracts.ts +240 -0
- package/src/validate/index.ts +45 -99
- package/src/vocabulary.ts +9 -0
- package/dist/validate/access.d.ts +0 -6
- package/dist/validate/access.d.ts.map +0 -1
- package/dist/validate/access.js +0 -238
- package/dist/validate/access.js.map +0 -1
- package/dist/validate/envelope.d.ts +0 -4
- package/dist/validate/envelope.d.ts.map +0 -1
- package/dist/validate/envelope.js +0 -55
- package/dist/validate/envelope.js.map +0 -1
- package/dist/validate/light.d.ts +0 -6
- package/dist/validate/light.d.ts.map +0 -1
- package/dist/validate/light.js +0 -28
- package/dist/validate/light.js.map +0 -1
- package/dist/validate/runs.d.ts +0 -16
- package/dist/validate/runs.d.ts.map +0 -1
- package/dist/validate/runs.js +0 -60
- package/dist/validate/runs.js.map +0 -1
- package/dist/validate/site.d.ts +0 -6
- package/dist/validate/site.d.ts.map +0 -1
- package/dist/validate/site.js +0 -63
- package/dist/validate/site.js.map +0 -1
- package/spec/README.md +0 -28
- package/spec/canonical-json.md +0 -98
- package/spec/composition.md +0 -121
- package/spec/derivation.md +0 -393
- package/spec/en/README.md +0 -30
- package/spec/en/canonical-json.md +0 -101
- package/spec/en/composition.md +0 -121
- package/spec/en/derivation.md +0 -393
- package/spec/en/language.md +0 -164
- package/spec/en/notation-v0.md +0 -145
- package/spec/en/scope.md +0 -229
- package/spec/en/semantics.md +0 -132
- package/spec/en/tools.md +0 -108
- package/spec/en/validation.md +0 -79
- package/spec/en/vocabulary.md +0 -103
- package/spec/language.md +0 -163
- package/spec/notation-v0.md +0 -184
- package/spec/scope.md +0 -229
- package/spec/semantics.md +0 -130
- package/spec/tools.md +0 -106
- package/spec/validation.md +0 -79
- package/spec/vocabulary.md +0 -114
- package/src/validate/access.ts +0 -279
- package/src/validate/envelope.ts +0 -59
- package/src/validate/light.ts +0 -43
- package/src/validate/runs.ts +0 -87
- package/src/validate/site.ts +0 -84
|
@@ -0,0 +1,1934 @@
|
|
|
1
|
+
import { checkDiagnostics, type Diagnostic } from "../core/diagnose.js";
|
|
2
|
+
import type { Model } from "../core/model.js";
|
|
3
|
+
import {
|
|
4
|
+
ANALYSIS_FORMAT,
|
|
5
|
+
COMPONENT_ID_PATTERN,
|
|
6
|
+
isComponentIdentity,
|
|
7
|
+
sameIdentity,
|
|
8
|
+
type AnalysisArtifact,
|
|
9
|
+
type AnalysisDefinition,
|
|
10
|
+
type AnalysisRef,
|
|
11
|
+
type AnalysisReport,
|
|
12
|
+
type AnalysisRequirement,
|
|
13
|
+
type AnalysisResult,
|
|
14
|
+
type ComponentIdentity,
|
|
15
|
+
type ContextEntry,
|
|
16
|
+
type ContextKey,
|
|
17
|
+
type ContextRead,
|
|
18
|
+
type ContextReader,
|
|
19
|
+
type ContextRequirement,
|
|
20
|
+
type ContextSnapshot,
|
|
21
|
+
type ContextSource,
|
|
22
|
+
type DeepReadonly,
|
|
23
|
+
type EffectiveRange,
|
|
24
|
+
type Evidence,
|
|
25
|
+
type ExecutionIssue,
|
|
26
|
+
type JurisdictionRef,
|
|
27
|
+
type MissingInput,
|
|
28
|
+
} from "../analysis/contracts.js";
|
|
29
|
+
import {
|
|
30
|
+
JsonBoundaryError,
|
|
31
|
+
assertJsonValue,
|
|
32
|
+
canonicalJsonValue,
|
|
33
|
+
codePointCompare,
|
|
34
|
+
type JsonValue,
|
|
35
|
+
} from "../analysis/json.js";
|
|
36
|
+
import {
|
|
37
|
+
ASSESSMENT_FORMAT,
|
|
38
|
+
AssessmentConfigError,
|
|
39
|
+
type AssessmentConfigProblem,
|
|
40
|
+
type AssessmentFinding,
|
|
41
|
+
type AssessmentOptions,
|
|
42
|
+
type AssessmentRegistry,
|
|
43
|
+
type AssessmentRegistryInput,
|
|
44
|
+
type AssessmentReport,
|
|
45
|
+
type AssessmentSummary,
|
|
46
|
+
type ComponentKind,
|
|
47
|
+
type Profile,
|
|
48
|
+
type ProfileRef,
|
|
49
|
+
type Rule,
|
|
50
|
+
type RuleEvaluation,
|
|
51
|
+
type RuleOutcome,
|
|
52
|
+
type RuleRun,
|
|
53
|
+
type RuleSet,
|
|
54
|
+
type RunAnalysisOptions,
|
|
55
|
+
} from "./contracts.js";
|
|
56
|
+
|
|
57
|
+
const SOURCE_KINDS = new Set(["authority", "survey", "brief", "user", "import", "other"]);
|
|
58
|
+
const OUTCOME_STATUSES = new Set(["pass", "fail", "indeterminate"]);
|
|
59
|
+
const MODEL_REQUIREMENTS = new Set(["consistent", "any"]);
|
|
60
|
+
const ANALYSIS_ACCEPTANCE = new Set(["complete", "partial"]);
|
|
61
|
+
const CONTEXT_PRESENCE = new Set(["required", "optional"]);
|
|
62
|
+
const FINDING_LEVELS = new Set(["violation", "caution"]);
|
|
63
|
+
const RULE_SET_PURPOSES = new Set(["design-lint", "operational-review", "code-screening", "compliance"]);
|
|
64
|
+
const SUBJECT_KINDS = new Set(["level", "space", "zone", "boundary", "opening", "run", "site"]);
|
|
65
|
+
const EVIDENCE_KINDS = new Set(["fact", "comparison", "route", "geometry", "missing"]);
|
|
66
|
+
const ISSUE_KINDS = new Set(["model-inconsistent", "dependency-unavailable", "missing-context", "invalid-context", "execution-error"]);
|
|
67
|
+
const COMPARISON_OPERATORS = new Set(["<", "<=", "=", ">=", ">", "inside", "outside"]);
|
|
68
|
+
|
|
69
|
+
interface RegistryIndexes {
|
|
70
|
+
readonly analyses: ReadonlyMap<string, AnalysisDefinition<JsonValue>>;
|
|
71
|
+
readonly ruleSets: ReadonlyMap<string, RuleSet>;
|
|
72
|
+
readonly profiles: ReadonlyMap<string, Profile>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
class LocalAssessmentRegistry implements AssessmentRegistry {
|
|
76
|
+
readonly #verified = true;
|
|
77
|
+
readonly analyses: readonly AnalysisDefinition<JsonValue>[];
|
|
78
|
+
readonly ruleSets: readonly RuleSet[];
|
|
79
|
+
readonly profiles: readonly Profile[];
|
|
80
|
+
|
|
81
|
+
constructor(input: AssessmentRegistryInput) {
|
|
82
|
+
try {
|
|
83
|
+
preflightRegistry(input);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
rethrowRegistryError(error, "registry preflight failed");
|
|
86
|
+
}
|
|
87
|
+
let snapshot: AssessmentRegistryInput;
|
|
88
|
+
try {
|
|
89
|
+
snapshot = {
|
|
90
|
+
analyses: Object.freeze(snapshotMap(input.analyses, copyAnalysisDefinition)),
|
|
91
|
+
ruleSets: Object.freeze(snapshotMap(input.ruleSets, copyRuleSet)),
|
|
92
|
+
profiles: Object.freeze(snapshotMap(input.profiles, copyProfile)),
|
|
93
|
+
};
|
|
94
|
+
} catch (error) {
|
|
95
|
+
throw new AssessmentConfigError({
|
|
96
|
+
code: "invalid-registry",
|
|
97
|
+
message: `registry snapshot failed: ${safeErrorMessage(error)}`,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
preflightRegistry(snapshot);
|
|
101
|
+
this.analyses = snapshot.analyses;
|
|
102
|
+
this.ruleSets = snapshot.ruleSets;
|
|
103
|
+
this.profiles = snapshot.profiles;
|
|
104
|
+
Object.freeze(this);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
static is(value: unknown): value is LocalAssessmentRegistry {
|
|
108
|
+
try {
|
|
109
|
+
return typeof value === "object" && value !== null && #verified in value;
|
|
110
|
+
} catch {
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function rethrowRegistryError(error: unknown, prefix: string): never {
|
|
117
|
+
let configurationError = false;
|
|
118
|
+
try {
|
|
119
|
+
configurationError = error instanceof AssessmentConfigError;
|
|
120
|
+
} catch {
|
|
121
|
+
configurationError = false;
|
|
122
|
+
}
|
|
123
|
+
if (configurationError) throw error;
|
|
124
|
+
throw new AssessmentConfigError({
|
|
125
|
+
code: "invalid-registry",
|
|
126
|
+
message: `${prefix}: ${safeErrorMessage(error)}`,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
class ContextDecoderExecutionError extends Error {
|
|
131
|
+
constructor(message: string) {
|
|
132
|
+
super(message);
|
|
133
|
+
this.name = "ContextDecoderExecutionError";
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function createAssessmentRegistry(input: AssessmentRegistryInput): AssessmentRegistry {
|
|
138
|
+
return new LocalAssessmentRegistry(input);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function runAnalysis<T extends JsonValue>(
|
|
142
|
+
model: Model,
|
|
143
|
+
analysis: AnalysisRef<T>,
|
|
144
|
+
options: RunAnalysisOptions,
|
|
145
|
+
): AnalysisReport<T> {
|
|
146
|
+
const configured = prepareConfiguration(options);
|
|
147
|
+
const allowed = reachableAnalyses(configured.profile, configured.indexes.analyses);
|
|
148
|
+
requireResolved(analysis, configured.indexes.analyses, configured.profile, "analysis");
|
|
149
|
+
if (!allowed.has(analysis.id) || !sameIdentity(allowed.get(analysis.id)!, analysis)) {
|
|
150
|
+
throw new AssessmentConfigError({
|
|
151
|
+
code: "missing-reference",
|
|
152
|
+
owner: identityOf(configured.profile),
|
|
153
|
+
targetKind: "analysis",
|
|
154
|
+
target: identityOf(analysis),
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
const prepared = diagnoseModel(model, configured);
|
|
158
|
+
|
|
159
|
+
const session = new AnalysisSession(
|
|
160
|
+
model,
|
|
161
|
+
prepared.modelState,
|
|
162
|
+
prepared.indexes.analyses,
|
|
163
|
+
allowed,
|
|
164
|
+
prepared.context,
|
|
165
|
+
prepared.usedContext,
|
|
166
|
+
);
|
|
167
|
+
const artifact = session.run(analysis);
|
|
168
|
+
const report: AnalysisReport<T> = {
|
|
169
|
+
schema: ANALYSIS_FORMAT,
|
|
170
|
+
profile: identityOf(prepared.profile),
|
|
171
|
+
model: modelReport(model, prepared.modelState, prepared.diagnostics),
|
|
172
|
+
context: contextTrace(prepared.context, prepared.usedContext),
|
|
173
|
+
result: { analysis: identityOf(analysis), artifact },
|
|
174
|
+
};
|
|
175
|
+
return immutableCanonical(report) as AnalysisReport<T>;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function assess(model: Model, options: AssessmentOptions): AssessmentReport {
|
|
179
|
+
const prepared = diagnoseModel(model, prepareConfiguration(options));
|
|
180
|
+
const allowed = reachableAnalyses(prepared.profile, prepared.indexes.analyses);
|
|
181
|
+
const session = new AnalysisSession(
|
|
182
|
+
model,
|
|
183
|
+
prepared.modelState,
|
|
184
|
+
prepared.indexes.analyses,
|
|
185
|
+
allowed,
|
|
186
|
+
prepared.context,
|
|
187
|
+
prepared.usedContext,
|
|
188
|
+
);
|
|
189
|
+
const selectedRuleSets = prepared.profile.ruleSets.map((reference) =>
|
|
190
|
+
requireResolved(reference, prepared.indexes.ruleSets, prepared.profile, "rule-set")
|
|
191
|
+
);
|
|
192
|
+
const orderedRules = selectedRuleSets.flatMap((ruleSet) =>
|
|
193
|
+
ruleSet.rules.map((rule) => ({ ruleSet, rule }))
|
|
194
|
+
);
|
|
195
|
+
|
|
196
|
+
// Complete the analysis phase before calling any rule. Shared dependencies still execute once.
|
|
197
|
+
for (const { rule } of orderedRules) {
|
|
198
|
+
for (const requirement of rule.analyses) session.run(requirement.analysis);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const runs: RuleRun[] = [];
|
|
202
|
+
const findings: AssessmentFinding[] = [];
|
|
203
|
+
for (const item of orderedRules) {
|
|
204
|
+
const run = executeRule(item.rule, item.ruleSet, session, prepared);
|
|
205
|
+
runs.push(run);
|
|
206
|
+
if (run.state !== "evaluated") continue;
|
|
207
|
+
for (const outcome of run.evaluation.outcomes) {
|
|
208
|
+
if (outcome.status !== "fail") continue;
|
|
209
|
+
findings.push({
|
|
210
|
+
rule: identityOf(item.rule),
|
|
211
|
+
ruleSet: identityOf(item.ruleSet),
|
|
212
|
+
level: item.rule.level,
|
|
213
|
+
outcome: outcome as RuleOutcome & { status: "fail" },
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const summary = summarize(prepared.modelState, runs);
|
|
219
|
+
const report: AssessmentReport = {
|
|
220
|
+
schema: ASSESSMENT_FORMAT,
|
|
221
|
+
profile: identityOf(prepared.profile),
|
|
222
|
+
ruleSets: selectedRuleSets.map(identityOf),
|
|
223
|
+
model: modelReport(model, prepared.modelState, prepared.diagnostics),
|
|
224
|
+
context: contextTrace(prepared.context, prepared.usedContext),
|
|
225
|
+
analyses: session.results,
|
|
226
|
+
rules: runs,
|
|
227
|
+
findings,
|
|
228
|
+
summary,
|
|
229
|
+
};
|
|
230
|
+
return immutableCanonical(report) as AssessmentReport;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
interface PreparedRun {
|
|
234
|
+
readonly indexes: RegistryIndexes;
|
|
235
|
+
readonly profile: Profile;
|
|
236
|
+
readonly context: ContextSnapshot;
|
|
237
|
+
readonly usedContext: Set<string>;
|
|
238
|
+
readonly diagnostics: readonly Diagnostic[];
|
|
239
|
+
readonly modelState: "consistent" | "inconsistent";
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
type PreparedConfiguration = Omit<PreparedRun, "diagnostics" | "modelState">;
|
|
243
|
+
|
|
244
|
+
function prepareConfiguration(options: AssessmentOptions): PreparedConfiguration {
|
|
245
|
+
try {
|
|
246
|
+
return prepareConfigurationUnchecked(options);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
let configurationError = false;
|
|
249
|
+
try {
|
|
250
|
+
configurationError = error instanceof AssessmentConfigError;
|
|
251
|
+
} catch {
|
|
252
|
+
configurationError = false;
|
|
253
|
+
}
|
|
254
|
+
if (configurationError) throw error;
|
|
255
|
+
throw new AssessmentConfigError({
|
|
256
|
+
code: "invalid-context",
|
|
257
|
+
path: "$options",
|
|
258
|
+
message: safeErrorMessage(error),
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function prepareConfigurationUnchecked(options: AssessmentOptions): PreparedConfiguration {
|
|
264
|
+
if (typeof options !== "object" || options === null || Array.isArray(options)) {
|
|
265
|
+
throw new AssessmentConfigError({
|
|
266
|
+
code: "invalid-context",
|
|
267
|
+
path: "$options",
|
|
268
|
+
message: "assessment options must be an object",
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
validateConfigKeys(
|
|
272
|
+
options as unknown as Record<string, unknown>,
|
|
273
|
+
["registry", "profile", "context"],
|
|
274
|
+
"$options",
|
|
275
|
+
["registry", "profile", "context"],
|
|
276
|
+
);
|
|
277
|
+
const indexes = indexRegistry(options.registry);
|
|
278
|
+
const profile = resolveProfile(options.profile, indexes.profiles);
|
|
279
|
+
const context = normalizeContextSnapshot(options.context);
|
|
280
|
+
const selectedRuleSets = profile.ruleSets.map((reference) =>
|
|
281
|
+
requireResolved(reference, indexes.ruleSets, profile, "rule-set")
|
|
282
|
+
);
|
|
283
|
+
validateApplicability(profile, selectedRuleSets, context);
|
|
284
|
+
return { indexes, profile, context, usedContext: new Set<string>() };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function diagnoseModel(model: Model, configured: PreparedConfiguration): PreparedRun {
|
|
288
|
+
// This is the only call site for a run. The resulting array is shared by every provider and rule.
|
|
289
|
+
const diagnostics = checkDiagnostics(model);
|
|
290
|
+
const modelState = diagnostics.some((diagnostic) => diagnostic.severity === "error")
|
|
291
|
+
? "inconsistent"
|
|
292
|
+
: "consistent";
|
|
293
|
+
return { ...configured, diagnostics, modelState };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function preflightRegistry(input: AssessmentRegistryInput): void {
|
|
297
|
+
if (!input || typeof input !== "object") {
|
|
298
|
+
throw new AssessmentConfigError({ code: "invalid-registry", message: "registry catalog must be an object" });
|
|
299
|
+
}
|
|
300
|
+
validateConfigKeys(
|
|
301
|
+
input as unknown as Record<string, unknown>,
|
|
302
|
+
["analyses", "ruleSets", "profiles"],
|
|
303
|
+
"$registry",
|
|
304
|
+
["analyses", "ruleSets", "profiles"],
|
|
305
|
+
);
|
|
306
|
+
requireProtocolArray(input.analyses, "$.analyses");
|
|
307
|
+
requireProtocolArray(input.ruleSets, "$.ruleSets");
|
|
308
|
+
requireProtocolArray(input.profiles, "$.profiles");
|
|
309
|
+
const analyses = uniqueMap(input.analyses, "analysis");
|
|
310
|
+
const ruleSets = uniqueMap(input.ruleSets, "rule-set");
|
|
311
|
+
const profiles = uniqueMap(input.profiles, "profile");
|
|
312
|
+
const contextKeys = new Map<string, ContextKey<JsonValue>>();
|
|
313
|
+
|
|
314
|
+
for (const definition of input.analyses) {
|
|
315
|
+
validateIdentity(definition, "analysis");
|
|
316
|
+
validateConfigKeys(
|
|
317
|
+
definition as unknown as Record<string, unknown>,
|
|
318
|
+
["id", "revision", "title", "model", "dependencies", "context", "run"],
|
|
319
|
+
`/analyses/${definition.id}`,
|
|
320
|
+
["id", "revision", "title", "model", "dependencies", "context", "run"],
|
|
321
|
+
);
|
|
322
|
+
validateNonEmpty(definition.title, `/analyses/${definition.id}/title`);
|
|
323
|
+
if (!MODEL_REQUIREMENTS.has(definition.model)) malformedDefinition(definition, "model must be consistent or any");
|
|
324
|
+
if (typeof definition.run !== "function") malformedDefinition(definition, "run must be a function");
|
|
325
|
+
requireProtocolArray(definition.dependencies, `/analyses/${definition.id}/dependencies`);
|
|
326
|
+
requireProtocolArray(definition.context, `/analyses/${definition.id}/context`);
|
|
327
|
+
validateRequirements(definition, definition.dependencies, analyses);
|
|
328
|
+
validateContextRequirements(definition, definition.context, contextKeys);
|
|
329
|
+
}
|
|
330
|
+
validateAnalysisCycles(input.analyses, analyses);
|
|
331
|
+
|
|
332
|
+
for (const ruleSet of input.ruleSets) {
|
|
333
|
+
validateIdentity(ruleSet, "rule-set");
|
|
334
|
+
validateConfigKeys(
|
|
335
|
+
ruleSet as unknown as Record<string, unknown>,
|
|
336
|
+
["id", "revision", "title", "purpose", "jurisdiction", "effective", "rules"],
|
|
337
|
+
`/ruleSets/${ruleSet.id}`,
|
|
338
|
+
["id", "revision", "title", "purpose", "rules"],
|
|
339
|
+
);
|
|
340
|
+
validateNonEmpty(ruleSet.title, `/ruleSets/${ruleSet.id}/title`);
|
|
341
|
+
if (!RULE_SET_PURPOSES.has(ruleSet.purpose)) malformedDefinition(ruleSet, "invalid rule-set purpose");
|
|
342
|
+
requireProtocolArray(ruleSet.rules, `/ruleSets/${ruleSet.id}/rules`);
|
|
343
|
+
validateEffective(ruleSet, ruleSet.effective);
|
|
344
|
+
validateJurisdiction(ruleSet, ruleSet.jurisdiction);
|
|
345
|
+
const rules = uniqueMap(ruleSet.rules, "rule");
|
|
346
|
+
for (const rule of rules.values()) {
|
|
347
|
+
validateIdentity(rule, "rule");
|
|
348
|
+
validateConfigKeys(
|
|
349
|
+
rule as unknown as Record<string, unknown>,
|
|
350
|
+
["id", "revision", "title", "level", "model", "analyses", "context", "authority", "evaluate"],
|
|
351
|
+
`/rules/${rule.id}`,
|
|
352
|
+
["id", "revision", "title", "level", "model", "analyses", "context", "authority", "evaluate"],
|
|
353
|
+
);
|
|
354
|
+
validateNonEmpty(rule.title, `/ruleSets/${ruleSet.id}/rules/${rule.id}/title`);
|
|
355
|
+
if (!FINDING_LEVELS.has(rule.level)) malformedDefinition(rule, "level must be violation or caution");
|
|
356
|
+
if (!MODEL_REQUIREMENTS.has(rule.model)) malformedDefinition(rule, "model must be consistent or any");
|
|
357
|
+
if (typeof rule.evaluate !== "function") malformedDefinition(rule, "evaluate must be a function");
|
|
358
|
+
requireProtocolArray(rule.analyses, `/rules/${rule.id}/analyses`);
|
|
359
|
+
requireProtocolArray(rule.context, `/rules/${rule.id}/context`);
|
|
360
|
+
requireProtocolArray(rule.authority, `/rules/${rule.id}/authority`);
|
|
361
|
+
validateRequirements(rule, rule.analyses, analyses);
|
|
362
|
+
validateContextRequirements(rule, rule.context, contextKeys);
|
|
363
|
+
for (const citation of rule.authority) validateAuthorityCitation(citation, rule);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
for (const profile of input.profiles) {
|
|
368
|
+
validateIdentity(profile, "profile");
|
|
369
|
+
validateConfigKeys(
|
|
370
|
+
profile as unknown as Record<string, unknown>,
|
|
371
|
+
["id", "revision", "title", "jurisdiction", "effective", "analyses", "ruleSets"],
|
|
372
|
+
`/profiles/${profile.id}`,
|
|
373
|
+
["id", "revision", "title", "analyses", "ruleSets"],
|
|
374
|
+
);
|
|
375
|
+
validateNonEmpty(profile.title, `/profiles/${profile.id}/title`);
|
|
376
|
+
validateEffective(profile, profile.effective);
|
|
377
|
+
validateJurisdiction(profile, profile.jurisdiction);
|
|
378
|
+
requireProtocolArray(profile.analyses, `/profiles/${profile.id}/analyses`);
|
|
379
|
+
requireProtocolArray(profile.ruleSets, `/profiles/${profile.id}/ruleSets`);
|
|
380
|
+
validateUniqueRefs(profile.analyses, "analysis");
|
|
381
|
+
validateUniqueRefs(profile.ruleSets, "rule-set");
|
|
382
|
+
|
|
383
|
+
for (const reference of profile.analyses) {
|
|
384
|
+
requireResolved(reference, analyses, profile, "analysis");
|
|
385
|
+
}
|
|
386
|
+
const allowed = reachableAnalyses(profile, analyses);
|
|
387
|
+
|
|
388
|
+
const selectedRules = new Map<string, Rule>();
|
|
389
|
+
for (const reference of profile.ruleSets) {
|
|
390
|
+
const ruleSet = requireResolved(reference, ruleSets, profile, "rule-set");
|
|
391
|
+
validateProfileRuleSetJurisdiction(profile, ruleSet);
|
|
392
|
+
for (const rule of ruleSet.rules) {
|
|
393
|
+
if (selectedRules.has(rule.id)) {
|
|
394
|
+
throw new AssessmentConfigError({ code: "duplicate-id", kind: "rule", id: rule.id });
|
|
395
|
+
}
|
|
396
|
+
selectedRules.set(rule.id, rule);
|
|
397
|
+
for (const requirement of rule.analyses) {
|
|
398
|
+
const selected = allowed.get(requirement.analysis.id);
|
|
399
|
+
if (!selected || !sameIdentity(selected, requirement.analysis)) {
|
|
400
|
+
throw missingReference(profile, "analysis", requirement.analysis);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// `profiles` is built above to validate duplicates even though resolution happens in the loop.
|
|
408
|
+
void profiles;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function uniqueMap<T extends ComponentIdentity>(items: readonly T[], kind: ComponentKind): Map<string, T> {
|
|
412
|
+
const out = new Map<string, T>();
|
|
413
|
+
for (const item of items) {
|
|
414
|
+
validateDefinitionShape(item, kind);
|
|
415
|
+
validateIdentity(item, kind);
|
|
416
|
+
if (out.has(item.id)) {
|
|
417
|
+
throw new AssessmentConfigError({ code: "duplicate-id", kind, id: item.id });
|
|
418
|
+
}
|
|
419
|
+
out.set(item.id, item);
|
|
420
|
+
}
|
|
421
|
+
return out;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function validateDefinitionShape(value: unknown, kind: ComponentKind): void {
|
|
425
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
426
|
+
throw new AssessmentConfigError({ code: "invalid-id", kind, id: String(value) });
|
|
427
|
+
}
|
|
428
|
+
const layouts: Partial<Record<ComponentKind, { allowed: readonly string[]; required: readonly string[] }>> = {
|
|
429
|
+
analysis: {
|
|
430
|
+
allowed: ["id", "revision", "title", "model", "dependencies", "context", "run"],
|
|
431
|
+
required: ["id", "revision", "title", "model", "dependencies", "context", "run"],
|
|
432
|
+
},
|
|
433
|
+
"rule-set": {
|
|
434
|
+
allowed: ["id", "revision", "title", "purpose", "jurisdiction", "effective", "rules"],
|
|
435
|
+
required: ["id", "revision", "title", "purpose", "rules"],
|
|
436
|
+
},
|
|
437
|
+
profile: {
|
|
438
|
+
allowed: ["id", "revision", "title", "jurisdiction", "effective", "analyses", "ruleSets"],
|
|
439
|
+
required: ["id", "revision", "title", "analyses", "ruleSets"],
|
|
440
|
+
},
|
|
441
|
+
rule: {
|
|
442
|
+
allowed: ["id", "revision", "title", "level", "model", "analyses", "context", "authority", "evaluate"],
|
|
443
|
+
required: ["id", "revision", "title", "level", "model", "analyses", "context", "authority", "evaluate"],
|
|
444
|
+
},
|
|
445
|
+
};
|
|
446
|
+
const layout = layouts[kind];
|
|
447
|
+
if (!layout) return;
|
|
448
|
+
validateConfigKeys(value as Record<string, unknown>, layout.allowed, `/components/${kind}`, layout.required);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function validateRequirements(
|
|
452
|
+
owner: ComponentIdentity,
|
|
453
|
+
requirements: readonly AnalysisRequirement[],
|
|
454
|
+
analyses: ReadonlyMap<string, AnalysisDefinition<JsonValue>>,
|
|
455
|
+
): void {
|
|
456
|
+
const seen = new Set<string>();
|
|
457
|
+
for (const requirement of requirements) {
|
|
458
|
+
if (typeof requirement !== "object" || requirement === null || Array.isArray(requirement)) {
|
|
459
|
+
malformedDefinition(owner, "analysis requirement must be an object");
|
|
460
|
+
}
|
|
461
|
+
validateConfigKeys(
|
|
462
|
+
requirement as unknown as Record<string, unknown>,
|
|
463
|
+
["analysis", "accept"],
|
|
464
|
+
`/components/${owner.id}/analyses`,
|
|
465
|
+
["analysis", "accept"],
|
|
466
|
+
);
|
|
467
|
+
validateReferenceIdentity(requirement.analysis, "analysis");
|
|
468
|
+
if (!ANALYSIS_ACCEPTANCE.has(requirement.accept)) malformedDefinition(owner, "analysis accept must be complete or partial");
|
|
469
|
+
if (seen.has(requirement.analysis.id)) {
|
|
470
|
+
throw new AssessmentConfigError({ code: "duplicate-id", kind: "analysis", id: requirement.analysis.id });
|
|
471
|
+
}
|
|
472
|
+
seen.add(requirement.analysis.id);
|
|
473
|
+
requireResolved(requirement.analysis, analyses, owner, "analysis");
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function validateContextRequirements(
|
|
478
|
+
owner: ComponentIdentity,
|
|
479
|
+
requirements: readonly ContextRequirement[],
|
|
480
|
+
known: Map<string, ContextKey<JsonValue>>,
|
|
481
|
+
): void {
|
|
482
|
+
const local = new Set<string>();
|
|
483
|
+
for (const requirement of requirements) {
|
|
484
|
+
if (typeof requirement !== "object" || requirement === null || Array.isArray(requirement)) {
|
|
485
|
+
malformedDefinition(owner, "context requirement must be an object");
|
|
486
|
+
}
|
|
487
|
+
validateConfigKeys(
|
|
488
|
+
requirement as unknown as Record<string, unknown>,
|
|
489
|
+
["key", "presence"],
|
|
490
|
+
`/components/${owner.id}/context`,
|
|
491
|
+
["key", "presence"],
|
|
492
|
+
);
|
|
493
|
+
const key = requirement.key as ContextKey<JsonValue>;
|
|
494
|
+
if (typeof key !== "object" || key === null || Array.isArray(key)) {
|
|
495
|
+
malformedDefinition(owner, "context key must be an object");
|
|
496
|
+
}
|
|
497
|
+
validateConfigKeys(
|
|
498
|
+
key as unknown as Record<string, unknown>,
|
|
499
|
+
["id", "revision", "description", "decode"],
|
|
500
|
+
"/contextKeys",
|
|
501
|
+
["id", "revision", "description", "decode"],
|
|
502
|
+
);
|
|
503
|
+
validateIdentity(key, "context-key");
|
|
504
|
+
validateNonEmpty(key.description, `/contextKeys/${key.id}/description`);
|
|
505
|
+
if (typeof key.decode !== "function") malformedDefinition(owner, "context key decode must be a function");
|
|
506
|
+
if (!CONTEXT_PRESENCE.has(requirement.presence)) malformedDefinition(owner, "context presence must be required or optional");
|
|
507
|
+
if (local.has(key.id)) {
|
|
508
|
+
throw new AssessmentConfigError({ code: "duplicate-id", kind: "context-key", id: key.id });
|
|
509
|
+
}
|
|
510
|
+
local.add(key.id);
|
|
511
|
+
const previous = known.get(key.id);
|
|
512
|
+
if (previous && (previous.revision !== key.revision || previous.decode !== key.decode)) {
|
|
513
|
+
throw new AssessmentConfigError({ code: "duplicate-id", kind: "context-key", id: key.id });
|
|
514
|
+
}
|
|
515
|
+
known.set(key.id, key);
|
|
516
|
+
}
|
|
517
|
+
void owner;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function validateAnalysisCycles(
|
|
521
|
+
definitions: readonly AnalysisDefinition<JsonValue>[],
|
|
522
|
+
analyses: ReadonlyMap<string, AnalysisDefinition<JsonValue>>,
|
|
523
|
+
): void {
|
|
524
|
+
const state = new Map<string, "grey" | "black">();
|
|
525
|
+
const stack: AnalysisDefinition<JsonValue>[] = [];
|
|
526
|
+
|
|
527
|
+
const visit = (definition: AnalysisDefinition<JsonValue>): void => {
|
|
528
|
+
const current = state.get(definition.id);
|
|
529
|
+
if (current === "black") return;
|
|
530
|
+
if (current === "grey") {
|
|
531
|
+
const start = stack.findIndex((entry) => entry.id === definition.id);
|
|
532
|
+
const cycle = [...stack.slice(start), definition].map(identityOf);
|
|
533
|
+
throw new AssessmentConfigError({
|
|
534
|
+
code: "dependency-cycle",
|
|
535
|
+
path: cycle as [ComponentIdentity, ComponentIdentity, ...ComponentIdentity[]],
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
state.set(definition.id, "grey");
|
|
539
|
+
stack.push(definition);
|
|
540
|
+
for (const requirement of definition.dependencies) {
|
|
541
|
+
visit(requireResolved(requirement.analysis, analyses, definition, "analysis"));
|
|
542
|
+
}
|
|
543
|
+
stack.pop();
|
|
544
|
+
state.set(definition.id, "black");
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
for (const definition of definitions) visit(definition);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function indexRegistry(registry: AssessmentRegistry): RegistryIndexes {
|
|
551
|
+
if (!LocalAssessmentRegistry.is(registry)) {
|
|
552
|
+
throw new AssessmentConfigError({
|
|
553
|
+
code: "invalid-registry",
|
|
554
|
+
message: "registry must be created by createAssessmentRegistry",
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
return {
|
|
558
|
+
analyses: new Map(registry.analyses.map((item) => [item.id, item])),
|
|
559
|
+
ruleSets: new Map(registry.ruleSets.map((item) => [item.id, item])),
|
|
560
|
+
profiles: new Map(registry.profiles.map((item) => [item.id, item])),
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function resolveProfile(
|
|
565
|
+
selection: ProfileRef | string,
|
|
566
|
+
profiles: ReadonlyMap<string, Profile>,
|
|
567
|
+
): Profile {
|
|
568
|
+
if (typeof selection !== "string") {
|
|
569
|
+
return requireResolved(selection, profiles, selection, "profile");
|
|
570
|
+
}
|
|
571
|
+
if (!COMPONENT_ID_PATTERN.test(selection)) {
|
|
572
|
+
throw new AssessmentConfigError({ code: "invalid-id", kind: "profile", id: selection });
|
|
573
|
+
}
|
|
574
|
+
const profile = profiles.get(selection);
|
|
575
|
+
if (!profile) {
|
|
576
|
+
const target = { id: selection, revision: "unknown" };
|
|
577
|
+
throw missingReference(target, "profile", target);
|
|
578
|
+
}
|
|
579
|
+
return profile;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function reachableAnalyses(
|
|
583
|
+
profile: Profile,
|
|
584
|
+
analyses: ReadonlyMap<string, AnalysisDefinition<JsonValue>>,
|
|
585
|
+
): Map<string, AnalysisRef> {
|
|
586
|
+
const reachable = new Map<string, AnalysisRef>();
|
|
587
|
+
const visit = (reference: AnalysisRef, owner: ComponentIdentity): void => {
|
|
588
|
+
const definition = requireResolved(reference, analyses, owner, "analysis");
|
|
589
|
+
const previous = reachable.get(definition.id);
|
|
590
|
+
if (previous) {
|
|
591
|
+
if (!sameIdentity(previous, definition)) {
|
|
592
|
+
throw new AssessmentConfigError({
|
|
593
|
+
code: "revision-mismatch",
|
|
594
|
+
owner: identityOf(owner),
|
|
595
|
+
targetKind: "analysis",
|
|
596
|
+
id: definition.id,
|
|
597
|
+
expected: previous.revision,
|
|
598
|
+
actual: definition.revision,
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
reachable.set(definition.id, identityOf(definition));
|
|
604
|
+
for (const dependency of definition.dependencies) visit(dependency.analysis, definition);
|
|
605
|
+
};
|
|
606
|
+
for (const root of profile.analyses) visit(root, profile);
|
|
607
|
+
return reachable;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function requireResolved<T extends ComponentIdentity>(
|
|
611
|
+
reference: ComponentIdentity,
|
|
612
|
+
definitions: ReadonlyMap<string, T>,
|
|
613
|
+
owner: ComponentIdentity,
|
|
614
|
+
kind: ComponentKind,
|
|
615
|
+
): T {
|
|
616
|
+
validateReferenceIdentity(reference, kind);
|
|
617
|
+
const found = definitions.get(reference.id);
|
|
618
|
+
if (!found) throw missingReference(owner, kind, reference);
|
|
619
|
+
if (found.revision !== reference.revision) {
|
|
620
|
+
throw new AssessmentConfigError({
|
|
621
|
+
code: "revision-mismatch",
|
|
622
|
+
owner: identityOf(owner),
|
|
623
|
+
targetKind: kind,
|
|
624
|
+
id: reference.id,
|
|
625
|
+
expected: reference.revision,
|
|
626
|
+
actual: found.revision,
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
return found;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
function validateReferenceIdentity(reference: unknown, kind: ComponentKind): asserts reference is ComponentIdentity {
|
|
633
|
+
if (typeof reference !== "object" || reference === null || Array.isArray(reference)) {
|
|
634
|
+
throw new AssessmentConfigError({ code: "invalid-id", kind, id: String(reference) });
|
|
635
|
+
}
|
|
636
|
+
validateConfigKeys(
|
|
637
|
+
reference as Record<string, unknown>,
|
|
638
|
+
["id", "revision"],
|
|
639
|
+
"/references",
|
|
640
|
+
["id", "revision"],
|
|
641
|
+
);
|
|
642
|
+
validateIdentity(reference, kind);
|
|
643
|
+
if (Reflect.ownKeys(reference).length !== 2) {
|
|
644
|
+
throw new AssessmentConfigError({
|
|
645
|
+
code: "invalid-context",
|
|
646
|
+
path: "/references",
|
|
647
|
+
message: "component references contain only id and revision",
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
function missingReference(
|
|
653
|
+
owner: ComponentIdentity,
|
|
654
|
+
targetKind: ComponentKind,
|
|
655
|
+
target: ComponentIdentity,
|
|
656
|
+
): AssessmentConfigError {
|
|
657
|
+
return new AssessmentConfigError({
|
|
658
|
+
code: "missing-reference",
|
|
659
|
+
owner: identityOf(owner),
|
|
660
|
+
targetKind,
|
|
661
|
+
target: identityOf(target),
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function validateIdentity(identity: unknown, kind: ComponentKind): asserts identity is ComponentIdentity {
|
|
666
|
+
if (!isComponentIdentity(identity)) {
|
|
667
|
+
const candidate = identity as { id?: unknown } | null | undefined;
|
|
668
|
+
const id = typeof candidate?.id === "string" ? candidate.id : String(candidate?.id);
|
|
669
|
+
throw new AssessmentConfigError({ code: "invalid-id", kind, id });
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
function validateUniqueRefs(references: readonly ComponentIdentity[], kind: ComponentKind): void {
|
|
674
|
+
const seen = new Set<string>();
|
|
675
|
+
for (const reference of references) {
|
|
676
|
+
validateReferenceIdentity(reference, kind);
|
|
677
|
+
if (seen.has(reference.id)) {
|
|
678
|
+
throw new AssessmentConfigError({ code: "duplicate-id", kind, id: reference.id });
|
|
679
|
+
}
|
|
680
|
+
seen.add(reference.id);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
function validateNonEmpty(value: unknown, path: string): asserts value is string {
|
|
685
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
686
|
+
throw new AssessmentConfigError({ code: "invalid-context", path, message: "must not be empty" });
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function requireProtocolArray(value: unknown, path: string): asserts value is readonly unknown[] {
|
|
691
|
+
if (!Array.isArray(value)) {
|
|
692
|
+
throw new AssessmentConfigError({ code: "invalid-context", path, message: "must be an array" });
|
|
693
|
+
}
|
|
694
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
695
|
+
if (typeof key === "symbol") {
|
|
696
|
+
throw new AssessmentConfigError({ code: "invalid-context", path, message: "array symbol fields are not allowed" });
|
|
697
|
+
}
|
|
698
|
+
if (key === "length" || !/^(0|[1-9]\d*)$/.test(key)) continue;
|
|
699
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
700
|
+
if (!descriptor || !descriptor.enumerable || !("value" in descriptor)) {
|
|
701
|
+
throw new AssessmentConfigError({
|
|
702
|
+
code: "invalid-context",
|
|
703
|
+
path: `${path}[${key}]`,
|
|
704
|
+
message: "array entries must be enumerable data properties",
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
for (let index = 0; index < value.length; index++) {
|
|
709
|
+
if (!Object.hasOwn(value, index)) {
|
|
710
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: `${path}[${index}]`, message: "arrays must not be sparse" });
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
function malformedDefinition(owner: ComponentIdentity, message: string): never {
|
|
716
|
+
throw new AssessmentConfigError({
|
|
717
|
+
code: "invalid-context",
|
|
718
|
+
path: `/components/${owner.id}`,
|
|
719
|
+
message,
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function validateAuthorityCitation(
|
|
724
|
+
citation: Rule["authority"][number],
|
|
725
|
+
owner: ComponentIdentity,
|
|
726
|
+
): void {
|
|
727
|
+
if (!citation || typeof citation !== "object") malformedDefinition(owner, "authority citation must be an object");
|
|
728
|
+
try {
|
|
729
|
+
assertJsonValue(citation);
|
|
730
|
+
assertAuthorityCitation(citation);
|
|
731
|
+
} catch (error) {
|
|
732
|
+
malformedDefinition(owner, `invalid authority citation: ${safeErrorMessage(error)}`);
|
|
733
|
+
}
|
|
734
|
+
validateJurisdiction(owner, citation.jurisdiction);
|
|
735
|
+
validateNonEmpty(citation.instrument, `/components/${owner.id}/authority/instrument`);
|
|
736
|
+
if (citation.provision !== undefined) validateNonEmpty(citation.provision, `/components/${owner.id}/authority/provision`);
|
|
737
|
+
if (citation.uri !== undefined) validateNonEmpty(citation.uri, `/components/${owner.id}/authority/uri`);
|
|
738
|
+
validateEffective(owner, citation.effective);
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
function validateEffective(owner: ComponentIdentity, effective: EffectiveRange | undefined): void {
|
|
742
|
+
if (effective === undefined) return;
|
|
743
|
+
if (typeof effective !== "object" || effective === null || Array.isArray(effective)) {
|
|
744
|
+
throw new AssessmentConfigError({
|
|
745
|
+
code: "invalid-context",
|
|
746
|
+
path: `/components/${owner.id}/effective`,
|
|
747
|
+
message: "effective must be an object when present",
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
try {
|
|
751
|
+
assertJsonValue(effective);
|
|
752
|
+
} catch (error) {
|
|
753
|
+
throw new AssessmentConfigError({
|
|
754
|
+
code: "invalid-context",
|
|
755
|
+
path: `/components/${owner.id}/effective`,
|
|
756
|
+
message: `effective must be plain JSON data: ${safeErrorMessage(error)}`,
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
validateConfigKeys(
|
|
760
|
+
effective as unknown as Record<string, unknown>,
|
|
761
|
+
["from", "to"],
|
|
762
|
+
`/components/${owner.id}/effective`,
|
|
763
|
+
["from"],
|
|
764
|
+
);
|
|
765
|
+
if (!isIsoDate(effective.from) || (effective.to !== undefined && !isIsoDate(effective.to))) {
|
|
766
|
+
throw new AssessmentConfigError({
|
|
767
|
+
code: "invalid-context",
|
|
768
|
+
path: `/components/${owner.id}/effective`,
|
|
769
|
+
message: "effective dates must be real YYYY-MM-DD calendar dates",
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
if (effective.to !== undefined && effective.from > effective.to) {
|
|
773
|
+
throw new AssessmentConfigError({
|
|
774
|
+
code: "invalid-context",
|
|
775
|
+
path: `/components/${owner.id}/effective`,
|
|
776
|
+
message: "effective.from must not be after effective.to",
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function validateJurisdiction(owner: ComponentIdentity, jurisdiction: JurisdictionRef | undefined): void {
|
|
782
|
+
if (jurisdiction === undefined) return;
|
|
783
|
+
if (typeof jurisdiction !== "object" || jurisdiction === null || Array.isArray(jurisdiction)) {
|
|
784
|
+
throw new AssessmentConfigError({
|
|
785
|
+
code: "invalid-context",
|
|
786
|
+
path: `/components/${owner.id}/jurisdiction`,
|
|
787
|
+
message: "jurisdiction must be an object when present",
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
try {
|
|
791
|
+
assertJsonValue(jurisdiction);
|
|
792
|
+
} catch (error) {
|
|
793
|
+
throw new AssessmentConfigError({
|
|
794
|
+
code: "invalid-context",
|
|
795
|
+
path: `/components/${owner.id}/jurisdiction`,
|
|
796
|
+
message: `jurisdiction must be plain JSON data: ${safeErrorMessage(error)}`,
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
const allowed = new Set(["country", "region", "locality", "authority"]);
|
|
800
|
+
if (typeof jurisdiction.country !== "string" || jurisdiction.country.trim() === "") {
|
|
801
|
+
throw new AssessmentConfigError({
|
|
802
|
+
code: "invalid-context",
|
|
803
|
+
path: `/components/${owner.id}/jurisdiction/country`,
|
|
804
|
+
message: "country is required",
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
for (const [field, value] of Object.entries(jurisdiction)) {
|
|
808
|
+
if (!allowed.has(field)) {
|
|
809
|
+
throw new AssessmentConfigError({
|
|
810
|
+
code: "invalid-context",
|
|
811
|
+
path: `/components/${owner.id}/jurisdiction/${field}`,
|
|
812
|
+
message: "unknown jurisdiction field",
|
|
813
|
+
});
|
|
814
|
+
}
|
|
815
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
816
|
+
throw new AssessmentConfigError({
|
|
817
|
+
code: "invalid-context",
|
|
818
|
+
path: `/components/${owner.id}/jurisdiction/${field}`,
|
|
819
|
+
message: "jurisdiction fields must be non-empty strings",
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
function validateProfileRuleSetJurisdiction(profile: Profile, ruleSet: RuleSet): void {
|
|
826
|
+
if (!profile.jurisdiction && ruleSet.jurisdiction) {
|
|
827
|
+
throw jurisdictionMismatch(profile, undefined, ruleSet.jurisdiction);
|
|
828
|
+
}
|
|
829
|
+
if (profile.jurisdiction && ruleSet.jurisdiction && !sameJurisdiction(profile.jurisdiction, ruleSet.jurisdiction)) {
|
|
830
|
+
throw jurisdictionMismatch(ruleSet, profile.jurisdiction, ruleSet.jurisdiction);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function validateApplicability(profile: Profile, ruleSets: readonly RuleSet[], context: ContextSnapshot): void {
|
|
835
|
+
validateAsOf(profile, profile.effective, context.asOf);
|
|
836
|
+
for (const ruleSet of ruleSets) validateAsOf(ruleSet, ruleSet.effective, context.asOf);
|
|
837
|
+
if (profile.jurisdiction && (!context.jurisdiction || !sameJurisdiction(profile.jurisdiction, context.jurisdiction))) {
|
|
838
|
+
throw jurisdictionMismatch(profile, profile.jurisdiction, context.jurisdiction);
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
function validateAsOf(owner: ComponentIdentity, effective: EffectiveRange | undefined, asOf: string): void {
|
|
843
|
+
if (!effective) return;
|
|
844
|
+
if (asOf < effective.from || (effective.to !== undefined && asOf > effective.to)) {
|
|
845
|
+
throw new AssessmentConfigError({
|
|
846
|
+
code: "effective-date-mismatch",
|
|
847
|
+
owner: identityOf(owner),
|
|
848
|
+
asOf,
|
|
849
|
+
effective: { ...effective },
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
function jurisdictionMismatch(
|
|
855
|
+
owner: ComponentIdentity,
|
|
856
|
+
expected: JurisdictionRef | undefined,
|
|
857
|
+
actual: JurisdictionRef | undefined,
|
|
858
|
+
): AssessmentConfigError {
|
|
859
|
+
return new AssessmentConfigError({
|
|
860
|
+
code: "jurisdiction-mismatch",
|
|
861
|
+
owner: identityOf(owner),
|
|
862
|
+
...(expected ? { expected: { ...expected } } : {}),
|
|
863
|
+
...(actual ? { actual: { ...actual } } : {}),
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function sameJurisdiction(a: JurisdictionRef, b: JurisdictionRef): boolean {
|
|
868
|
+
return a.country === b.country
|
|
869
|
+
&& a.region === b.region
|
|
870
|
+
&& a.locality === b.locality
|
|
871
|
+
&& a.authority === b.authority;
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
function isIsoDate(value: string): boolean {
|
|
875
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
876
|
+
if (!match) return false;
|
|
877
|
+
const year = Number(match[1]);
|
|
878
|
+
const month = Number(match[2]);
|
|
879
|
+
const day = Number(match[3]);
|
|
880
|
+
if (month < 1 || month > 12 || day < 1) return false;
|
|
881
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
882
|
+
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
883
|
+
return day <= days[month - 1]!;
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
function normalizeContextSnapshot(snapshot: ContextSnapshot): ContextSnapshot {
|
|
887
|
+
try {
|
|
888
|
+
return normalizeContextSnapshotUnchecked(snapshot);
|
|
889
|
+
} catch (error) {
|
|
890
|
+
let configurationError = false;
|
|
891
|
+
try {
|
|
892
|
+
configurationError = error instanceof AssessmentConfigError;
|
|
893
|
+
} catch {
|
|
894
|
+
configurationError = false;
|
|
895
|
+
}
|
|
896
|
+
if (configurationError) throw error;
|
|
897
|
+
throw new AssessmentConfigError({
|
|
898
|
+
code: "invalid-context",
|
|
899
|
+
path: "$",
|
|
900
|
+
message: safeErrorMessage(error),
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
function normalizeContextSnapshotUnchecked(snapshot: ContextSnapshot): ContextSnapshot {
|
|
906
|
+
try {
|
|
907
|
+
assertJsonValue(snapshot);
|
|
908
|
+
} catch (error) {
|
|
909
|
+
const boundary = error instanceof JsonBoundaryError ? error : undefined;
|
|
910
|
+
throw new AssessmentConfigError({
|
|
911
|
+
code: "invalid-context",
|
|
912
|
+
path: boundary?.path ?? "$",
|
|
913
|
+
message: boundary?.message ?? safeErrorMessage(error),
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
if (typeof snapshot !== "object" || snapshot === null || Array.isArray(snapshot)) {
|
|
917
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: "$", message: "context snapshot must be an object" });
|
|
918
|
+
}
|
|
919
|
+
validateConfigKeys(snapshot as unknown as Record<string, unknown>, ["schema", "asOf", "jurisdiction", "values"], "$", ["schema", "asOf", "values"]);
|
|
920
|
+
if (snapshot.schema !== "koyu-context/1") {
|
|
921
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: "$.schema", message: "expected koyu-context/1" });
|
|
922
|
+
}
|
|
923
|
+
if (!isIsoDate(snapshot.asOf)) {
|
|
924
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: "$.asOf", message: "expected a real YYYY-MM-DD date" });
|
|
925
|
+
}
|
|
926
|
+
if (snapshot.jurisdiction !== undefined) validateJurisdiction({ id: "koyu.context.snapshot", revision: "1" }, snapshot.jurisdiction);
|
|
927
|
+
if (typeof snapshot.values !== "object" || snapshot.values === null || Array.isArray(snapshot.values)) {
|
|
928
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: "$.values", message: "expected an object" });
|
|
929
|
+
}
|
|
930
|
+
for (const key of Object.keys(snapshot.values).sort(codePointCompare)) {
|
|
931
|
+
if (!COMPONENT_ID_PATTERN.test(key)) {
|
|
932
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: `$.values.${key}`, message: "key must be namespaced" });
|
|
933
|
+
}
|
|
934
|
+
validateContextEntry(snapshot.values[key], `$.values.${key}`);
|
|
935
|
+
}
|
|
936
|
+
return immutableCanonical(snapshot) as ContextSnapshot;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
function validateContextEntry(entry: ContextEntry | undefined, path: string): void {
|
|
940
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
941
|
+
throw new AssessmentConfigError({ code: "invalid-context", path, message: "expected a context entry" });
|
|
942
|
+
}
|
|
943
|
+
validateConfigKeys(entry as unknown as Record<string, unknown>, ["value", "source"], path, ["value", "source"]);
|
|
944
|
+
if (!Object.hasOwn(entry, "value")) {
|
|
945
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: `${path}.value`, message: "value is required" });
|
|
946
|
+
}
|
|
947
|
+
const source = entry.source;
|
|
948
|
+
if (!source || typeof source !== "object" || !SOURCE_KINDS.has(source.kind)) {
|
|
949
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: `${path}.source.kind`, message: "invalid provenance kind" });
|
|
950
|
+
}
|
|
951
|
+
validateConfigKeys(
|
|
952
|
+
source as unknown as Record<string, unknown>,
|
|
953
|
+
["kind", "ref", "observedAt", "retrievedAt"],
|
|
954
|
+
`${path}.source`,
|
|
955
|
+
["kind", "ref"],
|
|
956
|
+
);
|
|
957
|
+
if (typeof source.ref !== "string" || source.ref.trim() === "") {
|
|
958
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: `${path}.source.ref`, message: "provenance ref is required" });
|
|
959
|
+
}
|
|
960
|
+
for (const field of ["observedAt", "retrievedAt"] as const) {
|
|
961
|
+
const value = source[field];
|
|
962
|
+
if (value !== undefined && (typeof value !== "string" || value.trim() === "")) {
|
|
963
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: `${path}.source.${field}`, message: "must be a non-empty string" });
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
function validateConfigKeys(
|
|
969
|
+
record: Record<string, unknown>,
|
|
970
|
+
allowed: readonly string[],
|
|
971
|
+
path: string,
|
|
972
|
+
required: readonly string[] = [],
|
|
973
|
+
): void {
|
|
974
|
+
const allowedSet = new Set(allowed);
|
|
975
|
+
for (const key of Reflect.ownKeys(record)) {
|
|
976
|
+
if (typeof key !== "string") {
|
|
977
|
+
throw new AssessmentConfigError({
|
|
978
|
+
code: "invalid-context",
|
|
979
|
+
path,
|
|
980
|
+
message: "symbol fields are not allowed",
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
const descriptor = Object.getOwnPropertyDescriptor(record, key);
|
|
984
|
+
if (!descriptor || !descriptor.enumerable || !("value" in descriptor)) {
|
|
985
|
+
throw new AssessmentConfigError({
|
|
986
|
+
code: "invalid-context",
|
|
987
|
+
path: `${path}.${key}`,
|
|
988
|
+
message: "fields must be enumerable data properties",
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
if (!allowedSet.has(key)) {
|
|
992
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: `${path}.${key}`, message: "unexpected field" });
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
for (const key of required) {
|
|
996
|
+
if (!Object.hasOwn(record, key)) {
|
|
997
|
+
throw new AssessmentConfigError({ code: "invalid-context", path: `${path}.${key}`, message: "field is required" });
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
class AnalysisSession {
|
|
1003
|
+
readonly results: AnalysisResult<JsonValue>[] = [];
|
|
1004
|
+
private readonly cache = new Map<string, AnalysisResult<JsonValue>>();
|
|
1005
|
+
|
|
1006
|
+
constructor(
|
|
1007
|
+
private readonly model: Model,
|
|
1008
|
+
private readonly modelState: "consistent" | "inconsistent",
|
|
1009
|
+
private readonly definitions: ReadonlyMap<string, AnalysisDefinition<JsonValue>>,
|
|
1010
|
+
private readonly allowed: ReadonlyMap<string, AnalysisRef>,
|
|
1011
|
+
private readonly snapshot: ContextSnapshot,
|
|
1012
|
+
private readonly usedContext: Set<string>,
|
|
1013
|
+
) {}
|
|
1014
|
+
|
|
1015
|
+
run<T extends JsonValue>(reference: AnalysisRef<T>): AnalysisArtifact<T> {
|
|
1016
|
+
const cached = this.cache.get(reference.id);
|
|
1017
|
+
if (cached) return cached.artifact as AnalysisArtifact<T>;
|
|
1018
|
+
|
|
1019
|
+
const selected = this.allowed.get(reference.id);
|
|
1020
|
+
if (!selected || !sameIdentity(selected, reference)) {
|
|
1021
|
+
return this.store(reference, unavailable(
|
|
1022
|
+
[{ kind: "analysis", analysis: identityOf(reference), reason: "unavailable" }],
|
|
1023
|
+
[{ kind: "dependency-unavailable", message: `analysis is not selected by the profile: ${reference.id}` }],
|
|
1024
|
+
)) as AnalysisArtifact<T>;
|
|
1025
|
+
}
|
|
1026
|
+
const definition = requireResolved(reference, this.definitions, reference, "analysis");
|
|
1027
|
+
|
|
1028
|
+
const dependencyArtifacts = new Map<string, AnalysisArtifact<JsonValue>>();
|
|
1029
|
+
const dependencyMissing: MissingInput[] = [];
|
|
1030
|
+
for (const requirement of definition.dependencies) {
|
|
1031
|
+
const artifact = this.run(requirement.analysis);
|
|
1032
|
+
dependencyArtifacts.set(requirement.analysis.id, artifact);
|
|
1033
|
+
if (artifact.state === "unavailable" || (artifact.state === "partial" && requirement.accept === "complete")) {
|
|
1034
|
+
dependencyMissing.push({
|
|
1035
|
+
kind: "analysis",
|
|
1036
|
+
analysis: identityOf(requirement.analysis),
|
|
1037
|
+
reason: artifact.state === "partial" ? "partial" : "unavailable",
|
|
1038
|
+
});
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
if (dependencyMissing.length > 0) {
|
|
1042
|
+
return this.store(reference, unavailable(dependencyMissing, [{
|
|
1043
|
+
kind: "dependency-unavailable",
|
|
1044
|
+
message: `one or more dependencies are unavailable for ${reference.id}`,
|
|
1045
|
+
missing: dependencyMissing,
|
|
1046
|
+
}])) as AnalysisArtifact<T>;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
const context = contextReader(definition.context, this.snapshot, this.usedContext);
|
|
1050
|
+
let contextMissing: MissingInput[];
|
|
1051
|
+
try {
|
|
1052
|
+
contextMissing = requiredContextMissing(definition.context, context);
|
|
1053
|
+
} catch (error) {
|
|
1054
|
+
return this.store(reference, unavailable([executionMissing(reference, "context decoder failed")], [{
|
|
1055
|
+
kind: "execution-error",
|
|
1056
|
+
message: safeErrorMessage(error),
|
|
1057
|
+
}])) as AnalysisArtifact<T>;
|
|
1058
|
+
}
|
|
1059
|
+
if (contextMissing.length > 0) {
|
|
1060
|
+
return this.store(reference, unavailable(contextMissing, issuesForMissing(contextMissing))) as AnalysisArtifact<T>;
|
|
1061
|
+
}
|
|
1062
|
+
if (this.modelState === "inconsistent" && definition.model === "consistent") {
|
|
1063
|
+
const missing: MissingInput[] = [{ kind: "model", subjects: [{ kind: "model", ref: "/" }], reason: "core diagnostics contain an error" }];
|
|
1064
|
+
return this.store(reference, unavailable(missing, [{
|
|
1065
|
+
kind: "model-inconsistent",
|
|
1066
|
+
message: `${reference.id} requires a structurally consistent model`,
|
|
1067
|
+
missing,
|
|
1068
|
+
}])) as AnalysisArtifact<T>;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
const declared = new Map(definition.dependencies.map((requirement) => [requirement.analysis.id, requirement.analysis]));
|
|
1072
|
+
const get = <U extends JsonValue>(requested: AnalysisRef<U>): AnalysisArtifact<U> => {
|
|
1073
|
+
const requirement = declared.get(requested.id);
|
|
1074
|
+
if (!requirement || !sameIdentity(requirement, requested)) {
|
|
1075
|
+
throw new Error(`undeclared analysis dependency: ${requested.id}@${requested.revision}`);
|
|
1076
|
+
}
|
|
1077
|
+
return dependencyArtifacts.get(requested.id)! as AnalysisArtifact<U>;
|
|
1078
|
+
};
|
|
1079
|
+
|
|
1080
|
+
try {
|
|
1081
|
+
const artifact = normalizeArtifact(
|
|
1082
|
+
definition.run({ model: this.model as DeepReadonly<Model>, context, get }),
|
|
1083
|
+
);
|
|
1084
|
+
return this.store(reference, artifact) as AnalysisArtifact<T>;
|
|
1085
|
+
} catch (error) {
|
|
1086
|
+
return this.store(reference, unavailable([executionMissing(reference, "provider exception or invalid artifact")], [{
|
|
1087
|
+
kind: "execution-error",
|
|
1088
|
+
message: safeErrorMessage(error),
|
|
1089
|
+
}])) as AnalysisArtifact<T>;
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
private store(reference: AnalysisRef, artifact: AnalysisArtifact<JsonValue>): AnalysisArtifact<JsonValue> {
|
|
1094
|
+
const stableArtifact = immutableCanonical(artifact) as AnalysisArtifact<JsonValue>;
|
|
1095
|
+
const result: AnalysisResult<JsonValue> = { analysis: identityOf(reference), artifact: stableArtifact };
|
|
1096
|
+
this.cache.set(reference.id, result);
|
|
1097
|
+
this.results.push(result);
|
|
1098
|
+
return stableArtifact;
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
function executeRule(
|
|
1103
|
+
rule: Rule,
|
|
1104
|
+
ruleSet: RuleSet,
|
|
1105
|
+
session: AnalysisSession,
|
|
1106
|
+
prepared: PreparedRun,
|
|
1107
|
+
): RuleRun {
|
|
1108
|
+
const identity = { rule: identityOf(rule), ruleSet: identityOf(ruleSet) };
|
|
1109
|
+
const artifacts = new Map<string, AnalysisArtifact<JsonValue>>();
|
|
1110
|
+
const missing: MissingInput[] = [];
|
|
1111
|
+
const issues: ExecutionIssue[] = [];
|
|
1112
|
+
|
|
1113
|
+
if (prepared.modelState === "inconsistent" && rule.model === "consistent") {
|
|
1114
|
+
missing.push({ kind: "model", subjects: [{ kind: "model", ref: "/" }], reason: "core diagnostics contain an error" });
|
|
1115
|
+
issues.push({ kind: "model-inconsistent", message: `${rule.id} requires a structurally consistent model` });
|
|
1116
|
+
}
|
|
1117
|
+
for (const requirement of rule.analyses) {
|
|
1118
|
+
const artifact = session.run(requirement.analysis);
|
|
1119
|
+
artifacts.set(requirement.analysis.id, artifact);
|
|
1120
|
+
if (artifact.state === "unavailable" || (artifact.state === "partial" && requirement.accept === "complete")) {
|
|
1121
|
+
missing.push({
|
|
1122
|
+
kind: "analysis",
|
|
1123
|
+
analysis: identityOf(requirement.analysis),
|
|
1124
|
+
reason: artifact.state === "partial" ? "partial" : "unavailable",
|
|
1125
|
+
});
|
|
1126
|
+
issues.push({ kind: "dependency-unavailable", message: `${requirement.analysis.id} is not usable by ${rule.id}` });
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
const context = contextReader(rule.context, prepared.context, prepared.usedContext);
|
|
1131
|
+
let missingContext: MissingInput[];
|
|
1132
|
+
try {
|
|
1133
|
+
missingContext = requiredContextMissing(rule.context, context);
|
|
1134
|
+
} catch (error) {
|
|
1135
|
+
return {
|
|
1136
|
+
...identity,
|
|
1137
|
+
state: "error",
|
|
1138
|
+
issues: [{ kind: "execution-error", message: safeErrorMessage(error) }],
|
|
1139
|
+
};
|
|
1140
|
+
}
|
|
1141
|
+
missing.push(...missingContext);
|
|
1142
|
+
issues.push(...issuesForMissing(missingContext));
|
|
1143
|
+
if (missing.length > 0) {
|
|
1144
|
+
const orderedMissing = sortMissing(missing);
|
|
1145
|
+
const evaluation: Extract<RuleEvaluation, { applicability: "indeterminate" }> = {
|
|
1146
|
+
applicability: "indeterminate",
|
|
1147
|
+
reason: "one or more declared inputs are unavailable",
|
|
1148
|
+
missing: orderedMissing as [MissingInput, ...MissingInput[]],
|
|
1149
|
+
evidence: [],
|
|
1150
|
+
};
|
|
1151
|
+
return {
|
|
1152
|
+
...identity,
|
|
1153
|
+
state: "indeterminate",
|
|
1154
|
+
evaluation,
|
|
1155
|
+
issues: sortIssues(issues) as [ExecutionIssue, ...ExecutionIssue[]],
|
|
1156
|
+
};
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
const declared = new Map(rule.analyses.map((requirement) => [requirement.analysis.id, requirement.analysis]));
|
|
1160
|
+
const get = <T extends JsonValue>(reference: AnalysisRef<T>): AnalysisArtifact<T> => {
|
|
1161
|
+
const requirement = declared.get(reference.id);
|
|
1162
|
+
if (!requirement || !sameIdentity(requirement, reference)) {
|
|
1163
|
+
throw new Error(`undeclared analysis dependency: ${reference.id}@${reference.revision}`);
|
|
1164
|
+
}
|
|
1165
|
+
return artifacts.get(reference.id)! as AnalysisArtifact<T>;
|
|
1166
|
+
};
|
|
1167
|
+
|
|
1168
|
+
try {
|
|
1169
|
+
const evaluation = normalizeEvaluation(rule.evaluate({ context, get }));
|
|
1170
|
+
if (evaluation.applicability === "applicable") {
|
|
1171
|
+
return { ...identity, state: "evaluated", evaluation, issues: [] };
|
|
1172
|
+
}
|
|
1173
|
+
if (evaluation.applicability === "not-applicable") {
|
|
1174
|
+
return { ...identity, state: "not-applicable", evaluation, issues: [] };
|
|
1175
|
+
}
|
|
1176
|
+
const indeterminateIssues: [ExecutionIssue, ...ExecutionIssue[]] = [{
|
|
1177
|
+
kind: "koyu.rule-indeterminate",
|
|
1178
|
+
message: evaluation.reason,
|
|
1179
|
+
missing: evaluation.missing,
|
|
1180
|
+
}];
|
|
1181
|
+
return { ...identity, state: "indeterminate", evaluation, issues: indeterminateIssues };
|
|
1182
|
+
} catch (error) {
|
|
1183
|
+
return {
|
|
1184
|
+
...identity,
|
|
1185
|
+
state: "error",
|
|
1186
|
+
issues: [{ kind: "execution-error", message: safeErrorMessage(error) }],
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
function contextReader(
|
|
1192
|
+
requirements: readonly ContextRequirement[],
|
|
1193
|
+
snapshot: ContextSnapshot,
|
|
1194
|
+
used: Set<string>,
|
|
1195
|
+
): ContextReader {
|
|
1196
|
+
const declared = new Map(requirements.map((requirement) => [requirement.key.id, requirement.key]));
|
|
1197
|
+
const cache = new Map<string, ContextRead<JsonValue>>();
|
|
1198
|
+
|
|
1199
|
+
return {
|
|
1200
|
+
get<T extends JsonValue>(requested: ContextKey<T>): ContextRead<T> {
|
|
1201
|
+
const key = declared.get(requested.id);
|
|
1202
|
+
if (!key || !sameIdentity(key, requested)) {
|
|
1203
|
+
throw new Error(`undeclared context key: ${requested.id}@${requested.revision}`);
|
|
1204
|
+
}
|
|
1205
|
+
const previous = cache.get(key.id);
|
|
1206
|
+
if (previous) return previous as ContextRead<T>;
|
|
1207
|
+
used.add(key.id);
|
|
1208
|
+
const entry = snapshot.values[key.id];
|
|
1209
|
+
if (!entry) {
|
|
1210
|
+
const result = { state: "missing" } as const;
|
|
1211
|
+
cache.set(key.id, result);
|
|
1212
|
+
return result;
|
|
1213
|
+
}
|
|
1214
|
+
let decoded;
|
|
1215
|
+
try {
|
|
1216
|
+
decoded = key.decode(entry.value);
|
|
1217
|
+
} catch (error) {
|
|
1218
|
+
throw new ContextDecoderExecutionError(`${key.id}: ${safeErrorMessage(error)}`);
|
|
1219
|
+
}
|
|
1220
|
+
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
|
|
1221
|
+
throw new ContextDecoderExecutionError(`${key.id}: decoder returned a malformed result`);
|
|
1222
|
+
}
|
|
1223
|
+
try {
|
|
1224
|
+
assertJsonValue(decoded);
|
|
1225
|
+
} catch (error) {
|
|
1226
|
+
throw new ContextDecoderExecutionError(`${key.id}: decoder returned a malformed result (${safeErrorMessage(error)})`);
|
|
1227
|
+
}
|
|
1228
|
+
if (typeof decoded.ok !== "boolean") {
|
|
1229
|
+
throw new ContextDecoderExecutionError(`${key.id}: decoder returned a malformed result`);
|
|
1230
|
+
}
|
|
1231
|
+
if (!decoded.ok) {
|
|
1232
|
+
assertDecoderKeys(decoded as unknown as Record<string, unknown>, ["ok", "message"], key.id);
|
|
1233
|
+
if (typeof decoded.message !== "string") {
|
|
1234
|
+
throw new ContextDecoderExecutionError(`${key.id}: decoder rejection has no message`);
|
|
1235
|
+
}
|
|
1236
|
+
const result = { state: "invalid", entry, message: decoded.message } as const;
|
|
1237
|
+
cache.set(key.id, result);
|
|
1238
|
+
return result;
|
|
1239
|
+
}
|
|
1240
|
+
assertDecoderKeys(decoded as unknown as Record<string, unknown>, ["ok", "value"], key.id);
|
|
1241
|
+
try {
|
|
1242
|
+
assertJsonValue(decoded.value);
|
|
1243
|
+
} catch (error) {
|
|
1244
|
+
throw new ContextDecoderExecutionError(`${key.id}: decoder returned non-JSON data (${safeErrorMessage(error)})`);
|
|
1245
|
+
}
|
|
1246
|
+
const result = { state: "present", value: immutableCanonical(decoded.value) as JsonValue, entry } as const;
|
|
1247
|
+
cache.set(key.id, result);
|
|
1248
|
+
return result as ContextRead<T>;
|
|
1249
|
+
},
|
|
1250
|
+
};
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
function assertDecoderKeys(record: Record<string, unknown>, keys: readonly string[], keyId: string): void {
|
|
1254
|
+
try {
|
|
1255
|
+
assertJsonValue(record);
|
|
1256
|
+
assertExactKeys(record, keys, "context decoder result");
|
|
1257
|
+
assertRequiredKeys(record, keys, "context decoder result");
|
|
1258
|
+
} catch (error) {
|
|
1259
|
+
throw new ContextDecoderExecutionError(`${keyId}: ${safeErrorMessage(error)}`);
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
function requiredContextMissing(
|
|
1264
|
+
requirements: readonly ContextRequirement[],
|
|
1265
|
+
reader: ContextReader,
|
|
1266
|
+
): MissingInput[] {
|
|
1267
|
+
const missing: MissingInput[] = [];
|
|
1268
|
+
for (const requirement of requirements) {
|
|
1269
|
+
if (requirement.presence !== "required") continue;
|
|
1270
|
+
const read = reader.get(requirement.key);
|
|
1271
|
+
if (read.state === "missing") {
|
|
1272
|
+
missing.push({ kind: "context", key: requirement.key.id, reason: "missing" });
|
|
1273
|
+
} else if (read.state === "invalid") {
|
|
1274
|
+
missing.push({ kind: "context", key: requirement.key.id, reason: "invalid", message: read.message });
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
return missing;
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
function issuesForMissing(missing: readonly MissingInput[]): [ExecutionIssue, ...ExecutionIssue[]] {
|
|
1281
|
+
const issues = missing.map<ExecutionIssue>((entry) => ({
|
|
1282
|
+
kind: entry.kind === "context" && entry.reason === "invalid" ? "invalid-context" : "missing-context",
|
|
1283
|
+
message: missingMessage(entry),
|
|
1284
|
+
missing: [entry],
|
|
1285
|
+
}));
|
|
1286
|
+
return issues as [ExecutionIssue, ...ExecutionIssue[]];
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
function missingMessage(input: MissingInput): string {
|
|
1290
|
+
if (input.kind === "context") return `${input.key} is ${input.reason}`;
|
|
1291
|
+
if (input.kind === "analysis") return `${input.analysis.id} is ${input.reason}`;
|
|
1292
|
+
if (input.kind === "model") return input.reason;
|
|
1293
|
+
return `missing ${input.kind}`;
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
function unavailable(
|
|
1297
|
+
missing: readonly MissingInput[],
|
|
1298
|
+
issues: readonly [ExecutionIssue, ...ExecutionIssue[]],
|
|
1299
|
+
): AnalysisArtifact<JsonValue> {
|
|
1300
|
+
if (missing.length === 0) throw new TypeError("unavailable artifact requires at least one missing input");
|
|
1301
|
+
return {
|
|
1302
|
+
state: "unavailable",
|
|
1303
|
+
missing: sortMissing(missing) as [MissingInput, ...MissingInput[]],
|
|
1304
|
+
issues: sortIssues(issues) as [ExecutionIssue, ...ExecutionIssue[]],
|
|
1305
|
+
};
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
function executionMissing(component: ComponentIdentity, reason: string): MissingInput {
|
|
1309
|
+
return {
|
|
1310
|
+
kind: "koyu.execution",
|
|
1311
|
+
data: {
|
|
1312
|
+
componentId: component.id,
|
|
1313
|
+
componentRevision: component.revision,
|
|
1314
|
+
reason,
|
|
1315
|
+
},
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
function normalizeArtifact(value: unknown): AnalysisArtifact<JsonValue> {
|
|
1320
|
+
assertJsonValue(value);
|
|
1321
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1322
|
+
throw new TypeError("analysis artifact must be an object");
|
|
1323
|
+
}
|
|
1324
|
+
const artifact = value as unknown as Record<string, unknown>;
|
|
1325
|
+
if (artifact.state === "complete") {
|
|
1326
|
+
assertExactKeys(artifact, ["state", "value", "evidence"], "complete artifact");
|
|
1327
|
+
assertRequiredKeys(artifact, ["value", "evidence"], "complete artifact");
|
|
1328
|
+
assertJsonValue(artifact.value);
|
|
1329
|
+
return {
|
|
1330
|
+
state: "complete",
|
|
1331
|
+
value: canonicalJsonValue(artifact.value),
|
|
1332
|
+
evidence: normalizeEvidenceArray(artifact.evidence),
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
if (artifact.state === "partial") {
|
|
1336
|
+
assertExactKeys(artifact, ["state", "value", "missing", "evidence"], "partial artifact");
|
|
1337
|
+
assertRequiredKeys(artifact, ["value", "missing", "evidence"], "partial artifact");
|
|
1338
|
+
assertJsonValue(artifact.value);
|
|
1339
|
+
const missing = normalizeMissingArray(artifact.missing);
|
|
1340
|
+
if (missing.length === 0) throw new TypeError("partial artifact requires at least one missing input");
|
|
1341
|
+
return {
|
|
1342
|
+
state: "partial",
|
|
1343
|
+
value: canonicalJsonValue(artifact.value),
|
|
1344
|
+
missing: missing as [MissingInput, ...MissingInput[]],
|
|
1345
|
+
evidence: normalizeEvidenceArray(artifact.evidence),
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1348
|
+
if (artifact.state === "unavailable") {
|
|
1349
|
+
assertExactKeys(artifact, ["state", "missing", "issues"], "unavailable artifact");
|
|
1350
|
+
assertRequiredKeys(artifact, ["missing", "issues"], "unavailable artifact");
|
|
1351
|
+
const missing = normalizeMissingArray(artifact.missing);
|
|
1352
|
+
if (missing.length === 0) throw new TypeError("unavailable artifact requires at least one missing input");
|
|
1353
|
+
const issues = normalizeIssueArray(artifact.issues);
|
|
1354
|
+
if (issues.length === 0) throw new TypeError("unavailable artifact requires at least one issue");
|
|
1355
|
+
return {
|
|
1356
|
+
state: "unavailable",
|
|
1357
|
+
missing: missing as [MissingInput, ...MissingInput[]],
|
|
1358
|
+
issues: issues as [ExecutionIssue, ...ExecutionIssue[]],
|
|
1359
|
+
};
|
|
1360
|
+
}
|
|
1361
|
+
throw new TypeError("analysis artifact has an invalid state");
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
function normalizeEvaluation(value: unknown): RuleEvaluation {
|
|
1365
|
+
assertJsonValue(value);
|
|
1366
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1367
|
+
throw new TypeError("rule evaluation must be an object");
|
|
1368
|
+
}
|
|
1369
|
+
const evaluation = value as unknown as Record<string, unknown>;
|
|
1370
|
+
if (evaluation.applicability === "not-applicable") {
|
|
1371
|
+
assertExactKeys(evaluation, ["applicability", "reason", "evidence"], "not-applicable evaluation");
|
|
1372
|
+
assertRequiredKeys(evaluation, ["reason", "evidence"], "not-applicable evaluation");
|
|
1373
|
+
requireString(evaluation.reason, "not-applicable reason");
|
|
1374
|
+
return {
|
|
1375
|
+
applicability: "not-applicable",
|
|
1376
|
+
reason: evaluation.reason,
|
|
1377
|
+
evidence: normalizeEvidenceArray(evaluation.evidence),
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
if (evaluation.applicability === "indeterminate") {
|
|
1381
|
+
assertExactKeys(evaluation, ["applicability", "reason", "missing", "evidence"], "indeterminate evaluation");
|
|
1382
|
+
assertRequiredKeys(evaluation, ["reason", "missing", "evidence"], "indeterminate evaluation");
|
|
1383
|
+
requireString(evaluation.reason, "indeterminate reason");
|
|
1384
|
+
const missing = normalizeMissingArray(evaluation.missing);
|
|
1385
|
+
if (missing.length === 0) throw new TypeError("indeterminate evaluation requires missing input");
|
|
1386
|
+
return {
|
|
1387
|
+
applicability: "indeterminate",
|
|
1388
|
+
reason: evaluation.reason,
|
|
1389
|
+
missing: missing as [MissingInput, ...MissingInput[]],
|
|
1390
|
+
evidence: normalizeEvidenceArray(evaluation.evidence),
|
|
1391
|
+
};
|
|
1392
|
+
}
|
|
1393
|
+
if (evaluation.applicability === "applicable") {
|
|
1394
|
+
assertExactKeys(evaluation, ["applicability", "outcomes"], "applicable evaluation");
|
|
1395
|
+
assertRequiredKeys(evaluation, ["outcomes"], "applicable evaluation");
|
|
1396
|
+
if (!Array.isArray(evaluation.outcomes) || evaluation.outcomes.length === 0) {
|
|
1397
|
+
throw new TypeError("applicable evaluation requires at least one outcome");
|
|
1398
|
+
}
|
|
1399
|
+
const outcomes = evaluation.outcomes.map(normalizeOutcome);
|
|
1400
|
+
assertUniqueIds(outcomes, "rule outcome");
|
|
1401
|
+
outcomes.sort((a, b) => codePointCompare(a.id, b.id));
|
|
1402
|
+
return { applicability: "applicable", outcomes: outcomes as [RuleOutcome, ...RuleOutcome[]] };
|
|
1403
|
+
}
|
|
1404
|
+
throw new TypeError("rule evaluation has an invalid applicability");
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
function normalizeOutcome(value: unknown): RuleOutcome {
|
|
1408
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1409
|
+
throw new TypeError("rule outcome must be an object");
|
|
1410
|
+
}
|
|
1411
|
+
const outcome = value as Record<string, unknown>;
|
|
1412
|
+
assertExactKeys(outcome, ["id", "status", "subjects", "message", "evidence"], "rule outcome");
|
|
1413
|
+
assertRequiredKeys(outcome, ["id", "status", "subjects", "message", "evidence"], "rule outcome");
|
|
1414
|
+
requireString(outcome.id, "rule outcome id");
|
|
1415
|
+
requireString(outcome.message, "rule outcome message");
|
|
1416
|
+
if (typeof outcome.status !== "string" || !OUTCOME_STATUSES.has(outcome.status)) {
|
|
1417
|
+
throw new TypeError(`invalid outcome status: ${String(outcome.status)}`);
|
|
1418
|
+
}
|
|
1419
|
+
if (!Array.isArray(outcome.subjects) || outcome.subjects.length === 0) {
|
|
1420
|
+
throw new TypeError("rule outcome requires at least one subject");
|
|
1421
|
+
}
|
|
1422
|
+
const subjects = normalizeSubjects(outcome.subjects, "rule outcome");
|
|
1423
|
+
const evidence = normalizeEvidenceArray(outcome.evidence);
|
|
1424
|
+
if (evidence.length === 0) throw new TypeError("rule outcome requires at least one item of evidence");
|
|
1425
|
+
return {
|
|
1426
|
+
id: outcome.id,
|
|
1427
|
+
status: outcome.status as RuleOutcome["status"],
|
|
1428
|
+
subjects,
|
|
1429
|
+
message: outcome.message,
|
|
1430
|
+
evidence: evidence as [Evidence, ...Evidence[]],
|
|
1431
|
+
};
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
function normalizeEvidenceArray(value: unknown): Evidence[] {
|
|
1435
|
+
if (!Array.isArray(value)) throw new TypeError("evidence must be an array");
|
|
1436
|
+
const evidence = value.map(normalizeEvidence);
|
|
1437
|
+
assertUniqueIds(evidence, "evidence");
|
|
1438
|
+
evidence.sort((a, b) => codePointCompare(a.id, b.id));
|
|
1439
|
+
return evidence;
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
function normalizeMissingArray(value: unknown): MissingInput[] {
|
|
1443
|
+
if (!Array.isArray(value)) throw new TypeError("missing must be an array");
|
|
1444
|
+
return sortMissing(value.map(normalizeMissing));
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
function normalizeIssueArray(value: unknown): ExecutionIssue[] {
|
|
1448
|
+
if (!Array.isArray(value)) throw new TypeError("issues must be an array");
|
|
1449
|
+
return sortIssues(value.map(normalizeIssue));
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
function normalizeEvidence(value: unknown): Evidence {
|
|
1453
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1454
|
+
throw new TypeError("evidence item must be an object");
|
|
1455
|
+
}
|
|
1456
|
+
const record = value as Record<string, unknown>;
|
|
1457
|
+
requireString(record.id, "evidence id");
|
|
1458
|
+
requireString(record.kind, "evidence kind");
|
|
1459
|
+
assertExactIdentity(record.producedBy, "evidence producedBy");
|
|
1460
|
+
normalizeSubjects(record.subjects, "evidence");
|
|
1461
|
+
normalizeSources(record.sources);
|
|
1462
|
+
|
|
1463
|
+
switch (record.kind) {
|
|
1464
|
+
case "fact":
|
|
1465
|
+
assertExactKeys(record, ["id", "kind", "subjects", "sources", "producedBy", "name", "value"], "fact evidence");
|
|
1466
|
+
assertRequiredKeys(record, ["subjects", "sources", "producedBy", "name", "value"], "fact evidence");
|
|
1467
|
+
requireString(record.name, "fact evidence name");
|
|
1468
|
+
if (!("value" in record)) throw new TypeError("fact evidence requires value");
|
|
1469
|
+
break;
|
|
1470
|
+
case "comparison":
|
|
1471
|
+
assertExactKeys(record, ["id", "kind", "subjects", "sources", "producedBy", "observed", "operator", "required"], "comparison evidence");
|
|
1472
|
+
assertRequiredKeys(record, ["subjects", "sources", "producedBy", "observed", "operator", "required"], "comparison evidence");
|
|
1473
|
+
assertQuantity(record.observed, "comparison observed");
|
|
1474
|
+
if (typeof record.operator !== "string" || !COMPARISON_OPERATORS.has(record.operator)) {
|
|
1475
|
+
throw new TypeError("comparison evidence has an invalid operator");
|
|
1476
|
+
}
|
|
1477
|
+
assertRequiredQuantity(record.required);
|
|
1478
|
+
break;
|
|
1479
|
+
case "route":
|
|
1480
|
+
assertExactKeys(record, ["id", "kind", "subjects", "sources", "producedBy", "reachable", "profile", "path", "cost"], "route evidence");
|
|
1481
|
+
assertRequiredKeys(record, ["subjects", "sources", "producedBy", "reachable", "profile", "path"], "route evidence");
|
|
1482
|
+
if (typeof record.reachable !== "boolean") throw new TypeError("route reachable must be boolean");
|
|
1483
|
+
requireString(record.profile, "route profile");
|
|
1484
|
+
if (!Array.isArray(record.path) || !record.path.every((entry) => typeof entry === "string")) {
|
|
1485
|
+
throw new TypeError("route path must be a string array");
|
|
1486
|
+
}
|
|
1487
|
+
if (record.cost !== undefined) assertQuantity(record.cost, "route cost");
|
|
1488
|
+
break;
|
|
1489
|
+
case "geometry":
|
|
1490
|
+
assertExactKeys(record, ["id", "kind", "subjects", "sources", "producedBy", "geometry"], "geometry evidence");
|
|
1491
|
+
assertRequiredKeys(record, ["subjects", "sources", "producedBy", "geometry"], "geometry evidence");
|
|
1492
|
+
assertJsonObject(record.geometry, "geometry evidence");
|
|
1493
|
+
break;
|
|
1494
|
+
case "missing": {
|
|
1495
|
+
assertExactKeys(record, ["id", "kind", "subjects", "sources", "producedBy", "missing"], "missing evidence");
|
|
1496
|
+
assertRequiredKeys(record, ["subjects", "sources", "producedBy", "missing"], "missing evidence");
|
|
1497
|
+
const missing = normalizeMissingArray(record.missing);
|
|
1498
|
+
if (missing.length === 0) throw new TypeError("missing evidence requires at least one missing input");
|
|
1499
|
+
break;
|
|
1500
|
+
}
|
|
1501
|
+
default:
|
|
1502
|
+
if (!COMPONENT_ID_PATTERN.test(record.kind) || EVIDENCE_KINDS.has(record.kind)) {
|
|
1503
|
+
throw new TypeError(`invalid evidence kind: ${record.kind}`);
|
|
1504
|
+
}
|
|
1505
|
+
assertExactKeys(record, ["id", "kind", "subjects", "sources", "producedBy", "data"], "extension evidence");
|
|
1506
|
+
assertRequiredKeys(record, ["subjects", "sources", "producedBy", "data"], "extension evidence");
|
|
1507
|
+
assertJsonObject(record.data, "extension evidence data");
|
|
1508
|
+
}
|
|
1509
|
+
return canonicalJsonValue(record) as unknown as Evidence;
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
function normalizeSubjects(
|
|
1513
|
+
value: unknown,
|
|
1514
|
+
label: string,
|
|
1515
|
+
): [RuleOutcome["subjects"][number], ...RuleOutcome["subjects"][number][]] {
|
|
1516
|
+
if (!Array.isArray(value) || value.length === 0) throw new TypeError(`${label} requires at least one subject`);
|
|
1517
|
+
const subjects = value.map((subject) => {
|
|
1518
|
+
if (typeof subject !== "object" || subject === null || Array.isArray(subject)) {
|
|
1519
|
+
throw new TypeError("subject must be an object");
|
|
1520
|
+
}
|
|
1521
|
+
const record = subject as Record<string, unknown>;
|
|
1522
|
+
assertExactKeys(record, ["kind", "ref"], "subject");
|
|
1523
|
+
assertRequiredKeys(record, ["kind", "ref"], "subject");
|
|
1524
|
+
requireString(record.kind, "subject kind");
|
|
1525
|
+
requireString(record.ref, "subject ref");
|
|
1526
|
+
if (record.kind === "model") {
|
|
1527
|
+
if (record.ref !== "/") throw new TypeError("model subject ref must be /");
|
|
1528
|
+
} else if (!SUBJECT_KINDS.has(record.kind) && !COMPONENT_ID_PATTERN.test(record.kind)) {
|
|
1529
|
+
throw new TypeError(`invalid subject kind: ${record.kind}`);
|
|
1530
|
+
}
|
|
1531
|
+
return canonicalJsonValue(record) as RuleOutcome["subjects"][number];
|
|
1532
|
+
});
|
|
1533
|
+
return subjects as [RuleOutcome["subjects"][number], ...RuleOutcome["subjects"][number][]];
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
function normalizeSources(value: unknown): void {
|
|
1537
|
+
if (!Array.isArray(value) || value.length === 0) throw new TypeError("evidence requires at least one source");
|
|
1538
|
+
for (const source of value) normalizeSource(source);
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
function normalizeSource(value: unknown): void {
|
|
1542
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("source must be an object");
|
|
1543
|
+
const record = value as Record<string, unknown>;
|
|
1544
|
+
requireString(record.kind, "source kind");
|
|
1545
|
+
if (record.kind === "model") {
|
|
1546
|
+
assertExactKeys(record, ["kind", "subject", "location"], "model source");
|
|
1547
|
+
assertRequiredKeys(record, ["subject"], "model source");
|
|
1548
|
+
normalizeSubjects([record.subject], "model source");
|
|
1549
|
+
if (record.location !== undefined) {
|
|
1550
|
+
if (typeof record.location !== "object" || record.location === null || Array.isArray(record.location)) {
|
|
1551
|
+
throw new TypeError("source location must be an object");
|
|
1552
|
+
}
|
|
1553
|
+
const location = record.location as Record<string, unknown>;
|
|
1554
|
+
assertExactKeys(location, ["file", "line"], "source location");
|
|
1555
|
+
if (location.file !== undefined && typeof location.file !== "string") throw new TypeError("source location file must be a string");
|
|
1556
|
+
if (location.line !== undefined && (!Number.isInteger(location.line) || (location.line as number) < 1)) {
|
|
1557
|
+
throw new TypeError("source location line must be a positive integer");
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
return;
|
|
1561
|
+
}
|
|
1562
|
+
if (record.kind === "context") {
|
|
1563
|
+
assertExactKeys(record, ["kind", "key", "source"], "context source");
|
|
1564
|
+
assertRequiredKeys(record, ["key", "source"], "context source");
|
|
1565
|
+
if (typeof record.key !== "string" || !COMPONENT_ID_PATTERN.test(record.key)) throw new TypeError("context source key must be namespaced");
|
|
1566
|
+
assertContextSource(record.source);
|
|
1567
|
+
return;
|
|
1568
|
+
}
|
|
1569
|
+
if (record.kind === "authority") {
|
|
1570
|
+
assertExactKeys(record, ["kind", "citation"], "authority source");
|
|
1571
|
+
assertRequiredKeys(record, ["citation"], "authority source");
|
|
1572
|
+
assertAuthorityCitation(record.citation);
|
|
1573
|
+
return;
|
|
1574
|
+
}
|
|
1575
|
+
if (!COMPONENT_ID_PATTERN.test(record.kind)) throw new TypeError(`invalid source kind: ${record.kind}`);
|
|
1576
|
+
assertExactKeys(record, ["kind", "data"], "extension source");
|
|
1577
|
+
assertRequiredKeys(record, ["data"], "extension source");
|
|
1578
|
+
assertJsonObject(record.data, "extension source data");
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
function normalizeMissing(value: unknown): MissingInput {
|
|
1582
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1583
|
+
throw new TypeError("missing input must be an object");
|
|
1584
|
+
}
|
|
1585
|
+
const record = value as Record<string, unknown>;
|
|
1586
|
+
requireString(record.kind, "missing input kind");
|
|
1587
|
+
if (record.kind === "context") {
|
|
1588
|
+
assertExactKeys(record, ["kind", "key", "reason", "message"], "missing context input");
|
|
1589
|
+
assertRequiredKeys(record, ["key", "reason"], "missing context input");
|
|
1590
|
+
if (typeof record.key !== "string" || !COMPONENT_ID_PATTERN.test(record.key)) throw new TypeError("missing context key must be namespaced");
|
|
1591
|
+
if (record.reason !== "missing" && record.reason !== "invalid") throw new TypeError("invalid missing context reason");
|
|
1592
|
+
if (record.message !== undefined && typeof record.message !== "string") throw new TypeError("missing context message must be a string");
|
|
1593
|
+
} else if (record.kind === "model") {
|
|
1594
|
+
assertExactKeys(record, ["kind", "subjects", "reason"], "missing model input");
|
|
1595
|
+
assertRequiredKeys(record, ["subjects", "reason"], "missing model input");
|
|
1596
|
+
if (!Array.isArray(record.subjects)) throw new TypeError("missing model subjects must be an array");
|
|
1597
|
+
if (record.subjects.length > 0) normalizeSubjects(record.subjects, "missing model input");
|
|
1598
|
+
requireString(record.reason, "missing model reason");
|
|
1599
|
+
} else if (record.kind === "analysis") {
|
|
1600
|
+
assertExactKeys(record, ["kind", "analysis", "reason"], "missing analysis input");
|
|
1601
|
+
assertRequiredKeys(record, ["analysis", "reason"], "missing analysis input");
|
|
1602
|
+
assertExactIdentity(record.analysis, "missing analysis identity");
|
|
1603
|
+
if (record.reason !== "partial" && record.reason !== "unavailable") throw new TypeError("invalid missing analysis reason");
|
|
1604
|
+
} else {
|
|
1605
|
+
if (!COMPONENT_ID_PATTERN.test(record.kind)) throw new TypeError(`invalid missing input kind: ${record.kind}`);
|
|
1606
|
+
assertExactKeys(record, ["kind", "data"], "extension missing input");
|
|
1607
|
+
assertRequiredKeys(record, ["data"], "extension missing input");
|
|
1608
|
+
assertJsonObject(record.data, "extension missing data");
|
|
1609
|
+
}
|
|
1610
|
+
return canonicalJsonValue(record) as unknown as MissingInput;
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
function normalizeIssue(value: unknown): ExecutionIssue {
|
|
1614
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("issue must be an object");
|
|
1615
|
+
const record = value as Record<string, unknown>;
|
|
1616
|
+
assertExactKeys(record, ["kind", "message", "subjects", "missing"], "execution issue");
|
|
1617
|
+
assertRequiredKeys(record, ["kind", "message"], "execution issue");
|
|
1618
|
+
requireString(record.kind, "issue kind");
|
|
1619
|
+
requireString(record.message, "issue message");
|
|
1620
|
+
if (!ISSUE_KINDS.has(record.kind) && !COMPONENT_ID_PATTERN.test(record.kind)) {
|
|
1621
|
+
throw new TypeError(`invalid issue kind: ${record.kind}`);
|
|
1622
|
+
}
|
|
1623
|
+
if (record.subjects !== undefined) {
|
|
1624
|
+
if (!Array.isArray(record.subjects)) throw new TypeError("issue subjects must be an array");
|
|
1625
|
+
if (record.subjects.length > 0) normalizeSubjects(record.subjects, "issue");
|
|
1626
|
+
}
|
|
1627
|
+
if (record.missing !== undefined) normalizeMissingArray(record.missing);
|
|
1628
|
+
return canonicalJsonValue(record) as unknown as ExecutionIssue;
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
function assertQuantity(value: unknown, label: string): void {
|
|
1632
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${label} must be a quantity`);
|
|
1633
|
+
const record = value as Record<string, unknown>;
|
|
1634
|
+
assertExactKeys(record, ["value", "unit"], label);
|
|
1635
|
+
assertRequiredKeys(record, ["value", "unit"], label);
|
|
1636
|
+
if (typeof record.value !== "number" || !Number.isFinite(record.value)) throw new TypeError(`${label} value must be finite`);
|
|
1637
|
+
requireString(record.unit, `${label} unit`);
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
function assertRequiredQuantity(value: unknown): void {
|
|
1641
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("comparison required must be a quantity or bounds");
|
|
1642
|
+
const record = value as Record<string, unknown>;
|
|
1643
|
+
if ("value" in record) {
|
|
1644
|
+
assertQuantity(value, "comparison required");
|
|
1645
|
+
return;
|
|
1646
|
+
}
|
|
1647
|
+
assertExactKeys(record, ["minimum", "maximum"], "comparison bounds");
|
|
1648
|
+
if (record.minimum === undefined && record.maximum === undefined) throw new TypeError("comparison bounds require minimum or maximum");
|
|
1649
|
+
if (record.minimum !== undefined) assertQuantity(record.minimum, "comparison minimum");
|
|
1650
|
+
if (record.maximum !== undefined) assertQuantity(record.maximum, "comparison maximum");
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
function assertJsonObject(value: unknown, label: string): void {
|
|
1654
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${label} must be a JSON object`);
|
|
1655
|
+
assertJsonValue(value);
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
function assertContextSource(value: unknown): asserts value is ContextSource {
|
|
1659
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("context source must be an object");
|
|
1660
|
+
const source = value as Record<string, unknown>;
|
|
1661
|
+
assertExactKeys(source, ["kind", "ref", "observedAt", "retrievedAt"], "context source provenance");
|
|
1662
|
+
assertRequiredKeys(source, ["kind", "ref"], "context source provenance");
|
|
1663
|
+
if (typeof source.kind !== "string" || !SOURCE_KINDS.has(source.kind)) throw new TypeError("invalid context source kind");
|
|
1664
|
+
requireString(source.ref, "context source ref");
|
|
1665
|
+
if (source.observedAt !== undefined && typeof source.observedAt !== "string") throw new TypeError("observedAt must be a string");
|
|
1666
|
+
if (source.retrievedAt !== undefined && typeof source.retrievedAt !== "string") throw new TypeError("retrievedAt must be a string");
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
function assertAuthorityCitation(value: unknown): void {
|
|
1670
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("authority citation must be an object");
|
|
1671
|
+
const citation = value as Record<string, unknown>;
|
|
1672
|
+
assertExactKeys(citation, ["jurisdiction", "instrument", "provision", "uri", "effective"], "authority citation");
|
|
1673
|
+
assertRequiredKeys(citation, ["jurisdiction", "instrument"], "authority citation");
|
|
1674
|
+
assertJurisdiction(citation.jurisdiction);
|
|
1675
|
+
requireString(citation.instrument, "authority instrument");
|
|
1676
|
+
if (citation.provision !== undefined && typeof citation.provision !== "string") throw new TypeError("authority provision must be a string");
|
|
1677
|
+
if (citation.uri !== undefined && typeof citation.uri !== "string") throw new TypeError("authority uri must be a string");
|
|
1678
|
+
if (citation.effective !== undefined) assertEffective(citation.effective);
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
function assertJurisdiction(value: unknown): void {
|
|
1682
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("jurisdiction must be an object");
|
|
1683
|
+
const jurisdiction = value as Record<string, unknown>;
|
|
1684
|
+
assertExactKeys(jurisdiction, ["country", "region", "locality", "authority"], "jurisdiction");
|
|
1685
|
+
assertRequiredKeys(jurisdiction, ["country"], "jurisdiction");
|
|
1686
|
+
requireString(jurisdiction.country, "jurisdiction country");
|
|
1687
|
+
for (const field of ["region", "locality", "authority"] as const) {
|
|
1688
|
+
if (jurisdiction[field] !== undefined && typeof jurisdiction[field] !== "string") {
|
|
1689
|
+
throw new TypeError(`jurisdiction ${field} must be a string`);
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
}
|
|
1693
|
+
|
|
1694
|
+
function assertEffective(value: unknown): void {
|
|
1695
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError("effective range must be an object");
|
|
1696
|
+
const effective = value as Record<string, unknown>;
|
|
1697
|
+
assertExactKeys(effective, ["from", "to"], "effective range");
|
|
1698
|
+
assertRequiredKeys(effective, ["from"], "effective range");
|
|
1699
|
+
if (typeof effective.from !== "string" || !isIsoDate(effective.from)) throw new TypeError("effective from must be a date");
|
|
1700
|
+
if (effective.to !== undefined && (typeof effective.to !== "string" || !isIsoDate(effective.to))) throw new TypeError("effective to must be a date");
|
|
1701
|
+
if (typeof effective.to === "string" && effective.from > effective.to) throw new TypeError("effective range is reversed");
|
|
1702
|
+
}
|
|
1703
|
+
|
|
1704
|
+
function sortMissing(missing: readonly MissingInput[]): MissingInput[] {
|
|
1705
|
+
return [...missing].sort((a, b) => codePointCompare(stableString(a), stableString(b)));
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
function sortIssues(issues: readonly ExecutionIssue[]): ExecutionIssue[] {
|
|
1709
|
+
return [...issues].sort((a, b) => codePointCompare(stableString(a), stableString(b)));
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
function stableString(value: unknown): string {
|
|
1713
|
+
return JSON.stringify(canonicalJsonValue(value));
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
function assertUniqueIds(items: readonly { id: string }[], label: string): void {
|
|
1717
|
+
const seen = new Set<string>();
|
|
1718
|
+
for (const item of items) {
|
|
1719
|
+
if (seen.has(item.id)) throw new TypeError(`duplicate ${label} id: ${item.id}`);
|
|
1720
|
+
seen.add(item.id);
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
function assertExactIdentity(value: unknown, label: string): asserts value is ComponentIdentity {
|
|
1725
|
+
if (!isComponentIdentity(value)) throw new TypeError(`${label} is invalid`);
|
|
1726
|
+
assertExactKeys(value as unknown as Record<string, unknown>, ["id", "revision"], label);
|
|
1727
|
+
assertRequiredKeys(value as unknown as Record<string, unknown>, ["id", "revision"], label);
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
function assertExactKeys(record: Record<string, unknown>, allowed: readonly string[], label: string): void {
|
|
1731
|
+
const allowedSet = new Set(allowed);
|
|
1732
|
+
for (const key of Object.keys(record)) {
|
|
1733
|
+
if (!allowedSet.has(key)) throw new TypeError(`${label} has an unexpected field: ${key}`);
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
function assertRequiredKeys(record: Record<string, unknown>, required: readonly string[], label: string): void {
|
|
1738
|
+
for (const key of required) {
|
|
1739
|
+
if (!Object.hasOwn(record, key)) throw new TypeError(`${label} is missing field: ${key}`);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
function requireString(value: unknown, label: string): asserts value is string {
|
|
1744
|
+
if (typeof value !== "string" || value.trim() === "") throw new TypeError(`${label} must be a non-empty string`);
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
function summarize(modelState: "consistent" | "inconsistent", runs: readonly RuleRun[]): AssessmentSummary {
|
|
1748
|
+
const rules = { evaluated: 0, notApplicable: 0, indeterminate: 0, error: 0 };
|
|
1749
|
+
const outcomes = { pass: 0, fail: 0, indeterminate: 0 };
|
|
1750
|
+
for (const run of runs) {
|
|
1751
|
+
if (run.state === "evaluated") {
|
|
1752
|
+
rules.evaluated++;
|
|
1753
|
+
for (const outcome of run.evaluation.outcomes) outcomes[outcome.status]++;
|
|
1754
|
+
} else if (run.state === "not-applicable") {
|
|
1755
|
+
rules.notApplicable++;
|
|
1756
|
+
} else if (run.state === "indeterminate") {
|
|
1757
|
+
rules.indeterminate++;
|
|
1758
|
+
} else {
|
|
1759
|
+
rules.error++;
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
const incomplete = modelState === "inconsistent"
|
|
1763
|
+
|| rules.indeterminate > 0
|
|
1764
|
+
|| rules.error > 0
|
|
1765
|
+
|| outcomes.indeterminate > 0;
|
|
1766
|
+
return { state: incomplete ? "incomplete" : "complete", rules, outcomes };
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
function modelReport(
|
|
1770
|
+
model: Model,
|
|
1771
|
+
state: "consistent" | "inconsistent",
|
|
1772
|
+
diagnostics: readonly Diagnostic[],
|
|
1773
|
+
): AnalysisReport["model"] {
|
|
1774
|
+
return {
|
|
1775
|
+
languageVersion: model.version,
|
|
1776
|
+
...(model.name !== undefined ? { name: model.name } : {}),
|
|
1777
|
+
state,
|
|
1778
|
+
diagnostics: diagnostics.map((diagnostic) => ({
|
|
1779
|
+
code: diagnostic.code,
|
|
1780
|
+
severity: diagnostic.severity,
|
|
1781
|
+
message: diagnostic.message,
|
|
1782
|
+
...(diagnostic.line !== undefined ? { line: diagnostic.line } : {}),
|
|
1783
|
+
...(diagnostic.file !== undefined ? { file: diagnostic.file } : {}),
|
|
1784
|
+
...(diagnostic.path !== undefined ? { path: [...diagnostic.path] } : {}),
|
|
1785
|
+
...(diagnostic.related !== undefined
|
|
1786
|
+
? { related: diagnostic.related.map((item) => ({ ...item })) }
|
|
1787
|
+
: {}),
|
|
1788
|
+
})),
|
|
1789
|
+
};
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
function contextTrace(snapshot: ContextSnapshot, used: ReadonlySet<string>): ContextSnapshot {
|
|
1793
|
+
const values: Record<string, ContextEntry> = {};
|
|
1794
|
+
for (const key of [...used].sort(codePointCompare)) {
|
|
1795
|
+
const entry = snapshot.values[key];
|
|
1796
|
+
if (entry) values[key] = entry;
|
|
1797
|
+
}
|
|
1798
|
+
return {
|
|
1799
|
+
schema: "koyu-context/1",
|
|
1800
|
+
asOf: snapshot.asOf,
|
|
1801
|
+
...(snapshot.jurisdiction ? { jurisdiction: snapshot.jurisdiction } : {}),
|
|
1802
|
+
values,
|
|
1803
|
+
};
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
function identityOf(identity: ComponentIdentity): ComponentIdentity {
|
|
1807
|
+
return { id: identity.id, revision: identity.revision };
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
function refMap(references: readonly AnalysisRef[]): Map<string, AnalysisRef> {
|
|
1811
|
+
return new Map(references.map((reference) => [reference.id, reference]));
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
function safeErrorMessage(error: unknown): string {
|
|
1815
|
+
try {
|
|
1816
|
+
if (error instanceof Error) {
|
|
1817
|
+
const name = typeof error.name === "string" && error.name !== "" ? error.name : "Error";
|
|
1818
|
+
const message = typeof error.message === "string" ? error.message : "";
|
|
1819
|
+
return message === "" ? name : `${name}: ${message}`;
|
|
1820
|
+
}
|
|
1821
|
+
} catch {
|
|
1822
|
+
return "Error inspection failed";
|
|
1823
|
+
}
|
|
1824
|
+
return "Non-Error thrown";
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
function immutableCanonical(value: unknown): unknown {
|
|
1828
|
+
return deepFreeze(canonicalJsonValue(value));
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
function deepFreeze<T>(value: T): T {
|
|
1832
|
+
if (typeof value !== "object" || value === null || Object.isFrozen(value)) return value;
|
|
1833
|
+
if (Array.isArray(value)) {
|
|
1834
|
+
for (const item of value) deepFreeze(item);
|
|
1835
|
+
} else {
|
|
1836
|
+
for (const item of Object.values(value as Record<string, unknown>)) deepFreeze(item);
|
|
1837
|
+
}
|
|
1838
|
+
return Object.freeze(value);
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
function copyAnalysisDefinition(definition: AnalysisDefinition<JsonValue>): AnalysisDefinition<JsonValue> {
|
|
1842
|
+
return Object.freeze({
|
|
1843
|
+
id: definition.id,
|
|
1844
|
+
revision: definition.revision,
|
|
1845
|
+
title: definition.title,
|
|
1846
|
+
model: definition.model,
|
|
1847
|
+
dependencies: Object.freeze(snapshotMap(definition.dependencies, copyAnalysisRequirement)),
|
|
1848
|
+
context: Object.freeze(snapshotMap(definition.context, copyContextRequirement)),
|
|
1849
|
+
run: definition.run,
|
|
1850
|
+
});
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
function copyAnalysisRequirement(requirement: AnalysisRequirement): AnalysisRequirement {
|
|
1854
|
+
return Object.freeze({
|
|
1855
|
+
analysis: Object.freeze(identityOf(requirement.analysis)),
|
|
1856
|
+
accept: requirement.accept,
|
|
1857
|
+
});
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
function copyContextRequirement(requirement: ContextRequirement): ContextRequirement {
|
|
1861
|
+
return Object.freeze({
|
|
1862
|
+
key: Object.freeze({
|
|
1863
|
+
id: requirement.key.id,
|
|
1864
|
+
revision: requirement.key.revision,
|
|
1865
|
+
description: requirement.key.description,
|
|
1866
|
+
decode: requirement.key.decode,
|
|
1867
|
+
}),
|
|
1868
|
+
presence: requirement.presence,
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1872
|
+
function copyRule(rule: Rule): Rule {
|
|
1873
|
+
return Object.freeze({
|
|
1874
|
+
id: rule.id,
|
|
1875
|
+
revision: rule.revision,
|
|
1876
|
+
title: rule.title,
|
|
1877
|
+
level: rule.level,
|
|
1878
|
+
model: rule.model,
|
|
1879
|
+
analyses: Object.freeze(snapshotMap(rule.analyses, copyAnalysisRequirement)),
|
|
1880
|
+
context: Object.freeze(snapshotMap(rule.context, copyContextRequirement)),
|
|
1881
|
+
authority: Object.freeze(snapshotMap(rule.authority, copyAuthorityCitation)),
|
|
1882
|
+
evaluate: rule.evaluate,
|
|
1883
|
+
});
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
function copyRuleSet(ruleSet: RuleSet): RuleSet {
|
|
1887
|
+
return Object.freeze({
|
|
1888
|
+
id: ruleSet.id,
|
|
1889
|
+
revision: ruleSet.revision,
|
|
1890
|
+
title: ruleSet.title,
|
|
1891
|
+
purpose: ruleSet.purpose,
|
|
1892
|
+
...(ruleSet.jurisdiction !== undefined ? { jurisdiction: copyRecordLike(ruleSet.jurisdiction) } : {}),
|
|
1893
|
+
...(ruleSet.effective !== undefined ? { effective: copyRecordLike(ruleSet.effective) } : {}),
|
|
1894
|
+
rules: Object.freeze(snapshotMap(ruleSet.rules, copyRule)),
|
|
1895
|
+
});
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
function copyProfile(profile: Profile): Profile {
|
|
1899
|
+
return Object.freeze({
|
|
1900
|
+
id: profile.id,
|
|
1901
|
+
revision: profile.revision,
|
|
1902
|
+
title: profile.title,
|
|
1903
|
+
...(profile.jurisdiction !== undefined ? { jurisdiction: copyRecordLike(profile.jurisdiction) } : {}),
|
|
1904
|
+
...(profile.effective !== undefined ? { effective: copyRecordLike(profile.effective) } : {}),
|
|
1905
|
+
analyses: Object.freeze(snapshotMap(profile.analyses, (reference) => Object.freeze(identityOf(reference)))),
|
|
1906
|
+
ruleSets: Object.freeze(snapshotMap(profile.ruleSets, (reference) => Object.freeze(identityOf(reference)))),
|
|
1907
|
+
});
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
function copyAuthorityCitation(citation: Rule["authority"][number]): Rule["authority"][number] {
|
|
1911
|
+
const copied = {
|
|
1912
|
+
...citation,
|
|
1913
|
+
...(Object.hasOwn(citation, "jurisdiction") ? { jurisdiction: copyRecordLike(citation.jurisdiction) } : {}),
|
|
1914
|
+
...(Object.hasOwn(citation, "effective") ? { effective: copyRecordLike(citation.effective) } : {}),
|
|
1915
|
+
};
|
|
1916
|
+
return deepFreeze(copied);
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
function copyRecordLike<T>(value: T): T {
|
|
1920
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
|
|
1921
|
+
return immutableCanonical(value) as T;
|
|
1922
|
+
}
|
|
1923
|
+
|
|
1924
|
+
function snapshotMap<T, U>(items: readonly T[], mapper: (item: T) => U): U[] {
|
|
1925
|
+
if (!Array.isArray(items)) throw new TypeError("protocol collection must be an array");
|
|
1926
|
+
const length = items.length;
|
|
1927
|
+
if (!Number.isSafeInteger(length) || length < 0) throw new TypeError("protocol collection length is invalid");
|
|
1928
|
+
const out: U[] = [];
|
|
1929
|
+
for (let index = 0; index < length; index++) {
|
|
1930
|
+
if (!Object.hasOwn(items, index)) throw new TypeError("protocol collections must not be sparse");
|
|
1931
|
+
out.push(mapper(items[index]!));
|
|
1932
|
+
}
|
|
1933
|
+
return out;
|
|
1934
|
+
}
|