@astl/engine 0.0.0-stage → 0.1.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/CHANGELOG.md +35 -0
- package/LICENSE +202 -0
- package/README.md +40 -2
- package/dist/analyse.d.ts +68 -0
- package/dist/analyse.d.ts.map +1 -0
- package/dist/analyse.js +1179 -0
- package/dist/analyse.js.map +1 -0
- package/dist/checker.d.ts +19 -0
- package/dist/checker.d.ts.map +1 -0
- package/dist/checker.js +103 -0
- package/dist/checker.js.map +1 -0
- package/dist/compile.d.ts +16 -0
- package/dist/compile.d.ts.map +1 -0
- package/dist/compile.js +329 -0
- package/dist/compile.js.map +1 -0
- package/dist/conformance.d.ts +35 -0
- package/dist/conformance.d.ts.map +1 -0
- package/dist/conformance.js +101 -0
- package/dist/conformance.js.map +1 -0
- package/dist/engine.d.ts +13 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +231 -0
- package/dist/engine.js.map +1 -0
- package/dist/grade.d.ts +9 -0
- package/dist/grade.d.ts.map +1 -0
- package/dist/grade.js +192 -0
- package/dist/grade.js.map +1 -0
- package/dist/guard.d.ts +45 -0
- package/dist/guard.d.ts.map +1 -0
- package/dist/guard.js +327 -0
- package/dist/guard.js.map +1 -0
- package/dist/help.d.ts +32 -0
- package/dist/help.d.ts.map +1 -0
- package/dist/help.js +120 -0
- package/dist/help.js.map +1 -0
- package/dist/html.d.ts +31 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +246 -0
- package/dist/html.js.map +1 -0
- package/dist/ids.d.ts +35 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +126 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/kit/attributes.d.ts +6 -0
- package/dist/kit/attributes.d.ts.map +1 -0
- package/dist/kit/attributes.js +20 -0
- package/dist/kit/attributes.js.map +1 -0
- package/dist/kit/index.d.ts +43 -0
- package/dist/kit/index.d.ts.map +1 -0
- package/dist/kit/index.js +118 -0
- package/dist/kit/index.js.map +1 -0
- package/dist/limits.d.ts +17 -0
- package/dist/limits.d.ts.map +1 -0
- package/dist/limits.js +173 -0
- package/dist/limits.js.map +1 -0
- package/dist/messages/en.json +48 -0
- package/dist/messages/pl.json +48 -0
- package/dist/messages.d.ts +4 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +9 -0
- package/dist/messages.js.map +1 -0
- package/dist/round.d.ts +3 -0
- package/dist/round.d.ts.map +1 -0
- package/dist/round.js +5 -0
- package/dist/round.js.map +1 -0
- package/dist/slot-kinds.d.ts +58 -0
- package/dist/slot-kinds.d.ts.map +1 -0
- package/dist/slot-kinds.js +151 -0
- package/dist/slot-kinds.js.map +1 -0
- package/dist/text.d.ts +23 -0
- package/dist/text.d.ts.map +1 -0
- package/dist/text.js +236 -0
- package/dist/text.js.map +1 -0
- package/package.json +39 -3
- package/src/analyse.ts +1396 -0
- package/src/checker.ts +132 -0
- package/src/compile.ts +394 -0
- package/src/conformance.ts +120 -0
- package/src/engine.ts +274 -0
- package/src/grade.ts +229 -0
- package/src/guard.ts +356 -0
- package/src/help.ts +141 -0
- package/src/html.ts +274 -0
- package/src/ids.ts +144 -0
- package/src/index.ts +12 -0
- package/src/kit/attributes.ts +21 -0
- package/src/kit/index.ts +140 -0
- package/src/limits.ts +153 -0
- package/src/messages/en.json +48 -0
- package/src/messages/pl.json +48 -0
- package/src/messages.ts +9 -0
- package/src/round.ts +4 -0
- package/src/slot-kinds.ts +212 -0
- package/src/text.ts +234 -0
package/src/checker.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* localChecker: grading in the browser for hosts that opt in (HTML with answers, editor previews). It follows the
|
|
3
|
+
* grading protocol's rules so a player behaves the same as against a server.
|
|
4
|
+
*/
|
|
5
|
+
import {
|
|
6
|
+
type AnswerKey,
|
|
7
|
+
type AttemptPolicy,
|
|
8
|
+
type Checker,
|
|
9
|
+
CheckerError,
|
|
10
|
+
type CheckRequest,
|
|
11
|
+
type CheckResponse,
|
|
12
|
+
type Engine,
|
|
13
|
+
type GradeResult,
|
|
14
|
+
type HintRequest,
|
|
15
|
+
type HintResponse,
|
|
16
|
+
helpPolicy,
|
|
17
|
+
isAnswerKey,
|
|
18
|
+
isAttemptPolicy,
|
|
19
|
+
PRACTICE_POLICY,
|
|
20
|
+
ProblemCode,
|
|
21
|
+
type ProblemCodeValue,
|
|
22
|
+
type SubmitRequest,
|
|
23
|
+
type SubmitResponse,
|
|
24
|
+
} from '@astl/core';
|
|
25
|
+
import { helpShown, hintCount, isGradedElement, nextHint, resultHelp } from './help.js';
|
|
26
|
+
import { round6 } from './round.js';
|
|
27
|
+
|
|
28
|
+
export interface LocalChecker extends Checker {
|
|
29
|
+
/** Checks left in this attempt; null = unlimited. */
|
|
30
|
+
readonly checksLeft: number | null;
|
|
31
|
+
/** Hints used so far, by view element or page id: what grading takes off for. */
|
|
32
|
+
readonly hintsUsed: Readonly<Record<string, number>>;
|
|
33
|
+
hint(request: HintRequest): Promise<HintResponse>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
type LocalProblem =
|
|
37
|
+
| 'invalid_request'
|
|
38
|
+
| 'check_not_allowed'
|
|
39
|
+
| 'checks_exhausted'
|
|
40
|
+
| 'hints_not_allowed'
|
|
41
|
+
| 'hints_exhausted'
|
|
42
|
+
| 'not_found'
|
|
43
|
+
| 'attempt_closed';
|
|
44
|
+
|
|
45
|
+
/** Titles are for developers (RFC 9457); players show their own translated messages. */
|
|
46
|
+
const PROBLEMS: Readonly<Record<LocalProblem, { readonly status: number; readonly title: string }>> = {
|
|
47
|
+
invalid_request: { status: 400, title: 'A check names a page or an element, not both' },
|
|
48
|
+
check_not_allowed: { status: 403, title: 'Checking is not allowed in this attempt' },
|
|
49
|
+
checks_exhausted: { status: 403, title: 'No checks are left in this attempt' },
|
|
50
|
+
hints_not_allowed: { status: 403, title: 'Hints are not offered in this attempt' },
|
|
51
|
+
hints_exhausted: { status: 403, title: 'Every hint of it is used' },
|
|
52
|
+
not_found: { status: 404, title: 'Unknown page or element' },
|
|
53
|
+
attempt_closed: { status: 409, title: 'The attempt is already submitted' },
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
function problem(code: LocalProblem & ProblemCodeValue): CheckerError {
|
|
57
|
+
const { status, title } = PROBLEMS[code];
|
|
58
|
+
return new CheckerError({ type: `urn:astrolabe:problem:${code}`, title, status, code });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function passes(result: GradeResult, passMark: number): boolean {
|
|
62
|
+
return result.max === 0 || round6(result.score / result.max) >= passMark;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* A stateful Checker for one attempt: `check` only under a practice policy and within `maxChecks` (one interaction
|
|
67
|
+
* only with `checkScope: 'interaction'`), `hint` one at a time when the policy offers hints, one `submit`, the hints
|
|
68
|
+
* used taken off every grade, and `reveal`, `passMark`, `feedback` and `explanations` applied to the responses.
|
|
69
|
+
*/
|
|
70
|
+
export function localChecker(
|
|
71
|
+
engine: Engine,
|
|
72
|
+
key: AnswerKey,
|
|
73
|
+
policy: AttemptPolicy = PRACTICE_POLICY,
|
|
74
|
+
): LocalChecker {
|
|
75
|
+
if (!isAnswerKey(key)) throw new TypeError('localChecker: invalid answer key');
|
|
76
|
+
if (!isAttemptPolicy(policy)) throw new TypeError('localChecker: invalid attempt policy');
|
|
77
|
+
let checks = 0;
|
|
78
|
+
let submitted = false;
|
|
79
|
+
const used: Record<string, number> = {};
|
|
80
|
+
const checksLeft = (): number | null => {
|
|
81
|
+
if (policy.mode !== 'practice') return 0;
|
|
82
|
+
return policy.maxChecks === null ? null : Math.max(0, policy.maxChecks - checks);
|
|
83
|
+
};
|
|
84
|
+
return {
|
|
85
|
+
get checksLeft(): number | null {
|
|
86
|
+
return checksLeft();
|
|
87
|
+
},
|
|
88
|
+
get hintsUsed(): Readonly<Record<string, number>> {
|
|
89
|
+
return { ...used };
|
|
90
|
+
},
|
|
91
|
+
async check(request: CheckRequest): Promise<CheckResponse> {
|
|
92
|
+
const { page, element } = request;
|
|
93
|
+
if (policy.mode !== 'practice') throw problem(ProblemCode.checkNotAllowed);
|
|
94
|
+
if (submitted) throw problem(ProblemCode.attemptClosed);
|
|
95
|
+
if (page !== undefined && element !== undefined) throw problem(ProblemCode.invalidRequest);
|
|
96
|
+
if (element !== undefined && helpPolicy(policy).checkScope !== 'interaction') {
|
|
97
|
+
throw problem(ProblemCode.checkNotAllowed);
|
|
98
|
+
}
|
|
99
|
+
if (page !== undefined && !key.pages.includes(page)) throw problem(ProblemCode.notFound);
|
|
100
|
+
if (element !== undefined && !isGradedElement(key, element)) throw problem(ProblemCode.notFound);
|
|
101
|
+
if (checksLeft() === 0) throw problem(ProblemCode.checksExhausted);
|
|
102
|
+
checks++;
|
|
103
|
+
const scope = page !== undefined ? { page } : element !== undefined ? { element } : {};
|
|
104
|
+
const result = engine.grade(key, request.answers, { ...scope, hintsUsed: { ...used } });
|
|
105
|
+
const help = resultHelp(key, result, helpShown(policy, 'check'), element);
|
|
106
|
+
return { result, checksLeft: checksLeft(), ...help };
|
|
107
|
+
},
|
|
108
|
+
async hint(request: HintRequest): Promise<HintResponse> {
|
|
109
|
+
if (!helpPolicy(policy).hints) throw problem(ProblemCode.hintsNotAllowed);
|
|
110
|
+
if (submitted) throw problem(ProblemCode.attemptClosed);
|
|
111
|
+
const id = request.element;
|
|
112
|
+
if (hintCount(key, id) === 0) throw problem(ProblemCode.notFound);
|
|
113
|
+
const hint = nextHint(key, id, used[id] ?? 0);
|
|
114
|
+
if (hint === null) throw problem(ProblemCode.hintsExhausted);
|
|
115
|
+
used[id] = hint.index + 1;
|
|
116
|
+
return hint;
|
|
117
|
+
},
|
|
118
|
+
async submit(request: SubmitRequest): Promise<SubmitResponse> {
|
|
119
|
+
if (submitted || policy.mode === 'review') throw problem(ProblemCode.attemptClosed);
|
|
120
|
+
submitted = true;
|
|
121
|
+
const result = engine.grade(key, request.answers, { hintsUsed: { ...used } });
|
|
122
|
+
const revealed = policy.reveal !== 'nothing';
|
|
123
|
+
return {
|
|
124
|
+
result: revealed ? result : null,
|
|
125
|
+
solution: policy.reveal === 'answers' ? engine.solution(key) : null,
|
|
126
|
+
passed: revealed && policy.passMark !== null ? passes(result, policy.passMark) : null,
|
|
127
|
+
submittedAt: new Date().toISOString(),
|
|
128
|
+
...(revealed ? resultHelp(key, result, helpShown(policy, 'submit')) : {}),
|
|
129
|
+
};
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
}
|
package/src/compile.ts
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compile: view + answer key + metadata from an error-free analysis. Deterministic for (source, secret, salt).
|
|
3
|
+
*/
|
|
4
|
+
import {
|
|
5
|
+
type AnswerKey,
|
|
6
|
+
BLOCK_TAGS,
|
|
7
|
+
type Compilation,
|
|
8
|
+
type CompileContext,
|
|
9
|
+
type ComponentManifest,
|
|
10
|
+
DEFAULT_DOC_KIND,
|
|
11
|
+
DOC_TAG,
|
|
12
|
+
type ElementNode,
|
|
13
|
+
element,
|
|
14
|
+
FEEDBACK_VARIANTS,
|
|
15
|
+
FIGURE_TAG,
|
|
16
|
+
FORMAT_VERSION,
|
|
17
|
+
groupMax,
|
|
18
|
+
isElement,
|
|
19
|
+
KEY_FORMAT_VERSION,
|
|
20
|
+
type KeyHelp,
|
|
21
|
+
type KeySlot,
|
|
22
|
+
type Metadata,
|
|
23
|
+
type Node,
|
|
24
|
+
type NormalisationProfile,
|
|
25
|
+
PAGE_ATTRIBUTES,
|
|
26
|
+
PAGE_TAG,
|
|
27
|
+
type PageMetadata,
|
|
28
|
+
type ScoringGroup,
|
|
29
|
+
type SlotKind,
|
|
30
|
+
STYLE_TEMPLATE_ATTRIBUTE,
|
|
31
|
+
type UrlPolicy,
|
|
32
|
+
} from '@astl/core';
|
|
33
|
+
import type { ComponentRecord, DocRecord, HelpRecord } from './analyse.js';
|
|
34
|
+
import { guardView } from './guard.js';
|
|
35
|
+
import { helpAttributes } from './help.js';
|
|
36
|
+
import { parseHtml, serializeHtml } from './html.js';
|
|
37
|
+
import {
|
|
38
|
+
elementPath,
|
|
39
|
+
type Hmac,
|
|
40
|
+
idMessage,
|
|
41
|
+
opaqueId,
|
|
42
|
+
pagePath,
|
|
43
|
+
permutation,
|
|
44
|
+
seedWords,
|
|
45
|
+
sha256Hex,
|
|
46
|
+
} from './ids.js';
|
|
47
|
+
import { parseDecimalValue } from './kit/attributes.js';
|
|
48
|
+
import { round6 } from './round.js';
|
|
49
|
+
|
|
50
|
+
export interface CompileSetup {
|
|
51
|
+
readonly hmac: Hmac;
|
|
52
|
+
readonly salt: string;
|
|
53
|
+
readonly profile: NormalisationProfile;
|
|
54
|
+
readonly slotKinds: ReadonlyMap<string, SlotKind>;
|
|
55
|
+
/** Checks URLs that definitions write into views. */
|
|
56
|
+
readonly urlPolicy: UrlPolicy;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Definition bugs fail the compile loudly: they would leak answers or produce ungradeable keys. */
|
|
60
|
+
function definitionError(manifest: ComponentManifest, message: string): Error {
|
|
61
|
+
return new Error(`Component definition ${manifest.tag}: ${message}`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function own(attrs: Readonly<Record<string, string>>, name: string): string | undefined {
|
|
65
|
+
return Object.hasOwn(attrs, name) ? attrs[name] : undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A record's local ids: its children's, then the ones its definition derives (`localIds`), checked for clashes. */
|
|
69
|
+
function localIdsOf(rec: ComponentRecord): readonly string[] {
|
|
70
|
+
const derived = rec.definition.localIds?.(rec.element) ?? [];
|
|
71
|
+
const all = [...rec.localIds, ...derived];
|
|
72
|
+
if (new Set(all).size !== all.length) {
|
|
73
|
+
throw definitionError(rec.definition.manifest, 'localIds() returned an id twice or a child id');
|
|
74
|
+
}
|
|
75
|
+
return all;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function compileDocument(doc: DocRecord, setup: CompileSetup): Promise<Compilation> {
|
|
79
|
+
const locals = new Map([...doc.components.values()].map((rec) => [rec, localIdsOf(rec)]));
|
|
80
|
+
const localsOf = (rec: ComponentRecord): readonly string[] => locals.get(rec) ?? [];
|
|
81
|
+
const paths = doc.pages.map((p) => pagePath(p.sourceId));
|
|
82
|
+
for (const rec of doc.components.values()) {
|
|
83
|
+
paths.push(elementPath(rec.sourceId));
|
|
84
|
+
for (const local of localsOf(rec)) paths.push(elementPath(rec.sourceId, local));
|
|
85
|
+
}
|
|
86
|
+
const digestList = await Promise.all(paths.map((p) => setup.hmac(idMessage(setup.salt, p))));
|
|
87
|
+
const digests = new Map<string, Uint8Array>();
|
|
88
|
+
const ids = new Map<string, string>();
|
|
89
|
+
const taken = new Set<string>();
|
|
90
|
+
paths.forEach((path, i) => {
|
|
91
|
+
const digest = digestList[i] as Uint8Array;
|
|
92
|
+
const id = opaqueId(digest);
|
|
93
|
+
// 80-bit ids practically never collide; if they do, failing beats merging two slots.
|
|
94
|
+
if (taken.has(id)) throw new Error(`Opaque id collision for ${path}`);
|
|
95
|
+
taken.add(id);
|
|
96
|
+
digests.set(path, digest);
|
|
97
|
+
ids.set(path, id);
|
|
98
|
+
});
|
|
99
|
+
const idOf = (path: string): string => ids.get(path) as string;
|
|
100
|
+
|
|
101
|
+
const pageIds = doc.pages.map((p) => idOf(pagePath(p.sourceId)));
|
|
102
|
+
const bySource = new Map([...doc.components.values()].map((rec) => [rec.sourceId, rec]));
|
|
103
|
+
const contexts = new Map<ComponentRecord, CompileContext>();
|
|
104
|
+
for (const rec of doc.components.values()) {
|
|
105
|
+
contexts.set(rec, compileContext(rec, idOf, digests, setup.profile, bySource, localsOf));
|
|
106
|
+
}
|
|
107
|
+
const contextOf = (rec: ComponentRecord): CompileContext => contexts.get(rec) as CompileContext;
|
|
108
|
+
|
|
109
|
+
/** The help by view id (of an element or a page): its content into the key, what it offers into the view. */
|
|
110
|
+
const help: Record<string, KeyHelp> = {};
|
|
111
|
+
const offer = (id: string, record: HelpRecord | null): Record<string, string> => {
|
|
112
|
+
if (record === null) return {};
|
|
113
|
+
help[id] = keyHelp(record);
|
|
114
|
+
return helpAttributes({
|
|
115
|
+
hints: record.hints.map((h) => h.cost),
|
|
116
|
+
explanation: record.explanation !== null,
|
|
117
|
+
feedback: FEEDBACK_VARIANTS.filter((v) => Object.hasOwn(record.feedback, v)),
|
|
118
|
+
});
|
|
119
|
+
};
|
|
120
|
+
const viewNode = (node: Node): Node => {
|
|
121
|
+
if (node.type === 'text') return node;
|
|
122
|
+
const rec = doc.components.get(node);
|
|
123
|
+
if (rec === undefined) return element(node.tag, node.attrs, node.children.map(viewNode));
|
|
124
|
+
const ctx = contextOf(rec);
|
|
125
|
+
const view = rec.definition.toView(rec.element, ctx);
|
|
126
|
+
guardView(view, rec.element, rec.definition.manifest, { id: ctx.opaque(), urlPolicy: setup.urlPolicy });
|
|
127
|
+
return rec.help === null ? view : { ...view, attrs: { ...view.attrs, ...offer(ctx.opaque(), rec.help) } };
|
|
128
|
+
};
|
|
129
|
+
const viewPage = (page: ElementNode, index: number): ElementNode => {
|
|
130
|
+
const id = pageIds[index] as string;
|
|
131
|
+
const attrs: Record<string, string> = { id };
|
|
132
|
+
for (const name of PAGE_ATTRIBUTES) {
|
|
133
|
+
const value = own(page.attrs, name);
|
|
134
|
+
if (name !== 'id' && value !== undefined) attrs[name] = value;
|
|
135
|
+
}
|
|
136
|
+
const children = page.children.map(viewNode);
|
|
137
|
+
return element(PAGE_TAG, { ...attrs, ...offer(id, doc.pages[index]?.help ?? null) }, children);
|
|
138
|
+
};
|
|
139
|
+
const children = doc.explicitPages
|
|
140
|
+
? doc.root.children.map((n) => {
|
|
141
|
+
const index = n.type === 'element' ? doc.pageNodes.get(n) : undefined;
|
|
142
|
+
return index === undefined || n.type !== 'element' ? viewNode(n) : viewPage(n, index);
|
|
143
|
+
})
|
|
144
|
+
: [
|
|
145
|
+
viewPage(
|
|
146
|
+
element(PAGE_TAG, doc.pageStyle === null ? {} : { style: doc.pageStyle }, doc.root.children),
|
|
147
|
+
0,
|
|
148
|
+
),
|
|
149
|
+
];
|
|
150
|
+
const rootAttrs: Record<string, string> = { format: String(FORMAT_VERSION), lang: doc.lang, dir: doc.dir };
|
|
151
|
+
const style = own(doc.root.attrs, 'style');
|
|
152
|
+
if (style !== undefined) rootAttrs.style = style;
|
|
153
|
+
// Kept as written, also when this engine does not know it: the players that show the view may.
|
|
154
|
+
const template = own(doc.root.attrs, STYLE_TEMPLATE_ATTRIBUTE);
|
|
155
|
+
if (template !== undefined) rootAttrs[STYLE_TEMPLATE_ATTRIBUTE] = template;
|
|
156
|
+
// Only a kind other than the default: the views (and their hashes) of every exercise stay as they were.
|
|
157
|
+
if (doc.kind !== DEFAULT_DOC_KIND) rootAttrs.kind = doc.kind;
|
|
158
|
+
const root = element(DOC_TAG, rootAttrs, children);
|
|
159
|
+
|
|
160
|
+
const slots: Record<string, KeySlot> = {};
|
|
161
|
+
const groups: ScoringGroup[] = [];
|
|
162
|
+
/** Slots of ungraded types (open answers): in the key for the server, in no group. */
|
|
163
|
+
const open: string[] = [];
|
|
164
|
+
for (const rec of doc.components.values()) {
|
|
165
|
+
const manifest = rec.definition.manifest;
|
|
166
|
+
// Ungraded types without slot kinds (flash cards, media) have nothing to answer.
|
|
167
|
+
if (manifest.slotKinds.length === 0) continue;
|
|
168
|
+
const ctx = contextOf(rec);
|
|
169
|
+
const page = pageIds[rec.page] as string;
|
|
170
|
+
const groupId = ctx.opaque();
|
|
171
|
+
const ownIds = new Set([groupId, ...localsOf(rec).map((l) => ctx.opaque(l))]);
|
|
172
|
+
const specs = rec.definition.slots(rec.element, ctx);
|
|
173
|
+
if (specs.length === 0 && manifest.graded) {
|
|
174
|
+
throw definitionError(manifest, 'slots() returned no slots for a graded element');
|
|
175
|
+
}
|
|
176
|
+
const slotIds: string[] = [];
|
|
177
|
+
for (const spec of specs) {
|
|
178
|
+
const kind = setup.slotKinds.get(spec.kind);
|
|
179
|
+
if (kind === undefined || !manifest.slotKinds.includes(spec.kind)) {
|
|
180
|
+
throw definitionError(manifest, `slot kind "${spec.kind}" is not registered or not in its manifest`);
|
|
181
|
+
}
|
|
182
|
+
if (!kind.isKey(spec.key))
|
|
183
|
+
throw definitionError(manifest, `slot ${spec.id} has an invalid ${spec.kind} key`);
|
|
184
|
+
if (!ownIds.has(spec.id) || Object.hasOwn(slots, spec.id)) {
|
|
185
|
+
throw definitionError(manifest, `slot id ${spec.id} must be a fresh id from context.opaque()`);
|
|
186
|
+
}
|
|
187
|
+
slots[spec.id] = { kind: spec.kind, group: groupId, page, key: spec.key };
|
|
188
|
+
slotIds.push(spec.id);
|
|
189
|
+
}
|
|
190
|
+
// The manifest check makes ungraded types produce ungraded kinds only.
|
|
191
|
+
if (!manifest.graded || manifest.scoring === null) {
|
|
192
|
+
open.push(...slotIds);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const mode = own(rec.element.attrs, 'scoring') ?? manifest.scoring.default;
|
|
196
|
+
const rule = manifest.scoring.modes[mode];
|
|
197
|
+
if (rule === undefined) throw definitionError(manifest, `unknown scoring mode ${mode}`);
|
|
198
|
+
const points = parseDecimalValue(own(rec.element.attrs, 'points') ?? '1') ?? 1;
|
|
199
|
+
const parts = rec.definition.groups?.(rec.element, ctx) ?? null;
|
|
200
|
+
if (parts === null) {
|
|
201
|
+
groups.push({ id: groupId, rule, points, slots: slotIds, page });
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
// Graded in parts: every group a fresh local id with some of the element's slots, every slot in a group.
|
|
205
|
+
const mine = new Set(slotIds);
|
|
206
|
+
const grouped = new Set<string>();
|
|
207
|
+
const taken = new Set<string>();
|
|
208
|
+
for (const part of parts) {
|
|
209
|
+
if (part.id === groupId || mine.has(part.id) || !ownIds.has(part.id) || taken.has(part.id)) {
|
|
210
|
+
throw definitionError(
|
|
211
|
+
manifest,
|
|
212
|
+
`group id ${part.id} must be a fresh id from context.opaque(localId)`,
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
if (
|
|
216
|
+
part.slots.length === 0 ||
|
|
217
|
+
part.slots.some((s) => !mine.has(s)) ||
|
|
218
|
+
new Set(part.slots).size < part.slots.length
|
|
219
|
+
) {
|
|
220
|
+
throw definitionError(manifest, `group ${part.id} must hold some of the element's slots, each once`);
|
|
221
|
+
}
|
|
222
|
+
taken.add(part.id);
|
|
223
|
+
for (const s of part.slots) grouped.add(s);
|
|
224
|
+
groups.push({ id: part.id, rule, points, slots: [...part.slots], page });
|
|
225
|
+
}
|
|
226
|
+
if (parts.length === 0 || grouped.size < mine.size) {
|
|
227
|
+
throw definitionError(manifest, 'groups() must hold every slot of the element');
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Unwrapping can leave nesting the HTML parser rebuilds (a list item inside a list item, once a table around it is
|
|
232
|
+
// gone). Serve the tree a browser builds from the view, so the hash covers what students actually get.
|
|
233
|
+
const view = serializeHtml(parseHtml(serializeHtml([root])));
|
|
234
|
+
const viewHash = await sha256Hex(view);
|
|
235
|
+
const key: AnswerKey = {
|
|
236
|
+
format: KEY_FORMAT_VERSION,
|
|
237
|
+
lang: doc.lang,
|
|
238
|
+
viewHash,
|
|
239
|
+
pages: pageIds,
|
|
240
|
+
slots,
|
|
241
|
+
groups,
|
|
242
|
+
// Only with help, so the keys of sources without any stay as they were.
|
|
243
|
+
...(Object.keys(help).length === 0 ? {} : { help }),
|
|
244
|
+
};
|
|
245
|
+
return { view, viewHash, key, metadata: metadataOf(doc, root, pageIds, key, open) };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const isBlock = (node: Node): boolean =>
|
|
249
|
+
isElement(node) && (BLOCK_TAGS.has(node.tag) || node.tag === FIGURE_TAG);
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* The HTML of help content as a browser rebuilds it, like the view's (see the end of `compileDocument`). Blocks lose
|
|
253
|
+
* the white space around them: how a source is laid out (or an editor writes it) does not change the key.
|
|
254
|
+
*/
|
|
255
|
+
const helpHtml = (content: readonly Node[]): string => {
|
|
256
|
+
const blocks = content.some(isBlock);
|
|
257
|
+
const kept = blocks ? content.filter((n) => isElement(n) || n.value.trim() !== '') : content;
|
|
258
|
+
return serializeHtml(parseHtml(serializeHtml(kept)));
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
function keyHelp(record: HelpRecord): KeyHelp {
|
|
262
|
+
const feedback: Record<string, string> = {};
|
|
263
|
+
for (const variant of FEEDBACK_VARIANTS) {
|
|
264
|
+
const content = record.feedback[variant];
|
|
265
|
+
if (content !== undefined) feedback[variant] = helpHtml(content);
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
hints: record.hints.map((h) => ({ html: helpHtml(h.content), cost: h.cost })),
|
|
269
|
+
explanation: record.explanation === null ? null : helpHtml(record.explanation),
|
|
270
|
+
feedback,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function compileContext(
|
|
275
|
+
rec: ComponentRecord,
|
|
276
|
+
idOf: (path: string) => string,
|
|
277
|
+
digests: ReadonlyMap<string, Uint8Array>,
|
|
278
|
+
profile: NormalisationProfile,
|
|
279
|
+
bySource: ReadonlyMap<string, ComponentRecord>,
|
|
280
|
+
localsOf: (rec: ComponentRecord) => readonly string[],
|
|
281
|
+
): CompileContext {
|
|
282
|
+
const self = elementPath(rec.sourceId);
|
|
283
|
+
const seed = seedWords(digests.get(self) as Uint8Array);
|
|
284
|
+
const locals = new Set(localsOf(rec));
|
|
285
|
+
return {
|
|
286
|
+
lang: rec.lang,
|
|
287
|
+
dir: rec.dir,
|
|
288
|
+
profile,
|
|
289
|
+
opaque(localId?: string): string {
|
|
290
|
+
if (localId === undefined) return idOf(self);
|
|
291
|
+
if (!locals.has(localId)) {
|
|
292
|
+
throw definitionError(rec.definition.manifest, `"${localId}" is not a local id of ${rec.sourceId}`);
|
|
293
|
+
}
|
|
294
|
+
return idOf(elementPath(rec.sourceId, localId));
|
|
295
|
+
},
|
|
296
|
+
opaqueOf(id: string, localId?: string): string {
|
|
297
|
+
const other = bySource.get(id);
|
|
298
|
+
if (other === undefined || (localId !== undefined && !localsOf(other).includes(localId))) {
|
|
299
|
+
const what = localId === undefined ? `component "${id}"` : `local id "${localId}" of "${id}"`;
|
|
300
|
+
throw definitionError(rec.definition.manifest, `there is no ${what}`);
|
|
301
|
+
}
|
|
302
|
+
return idOf(elementPath(id, localId));
|
|
303
|
+
},
|
|
304
|
+
permute<T>(items: readonly T[], options: { avoidOriginal?: boolean; salt?: string } = {}): T[] {
|
|
305
|
+
const order = permutation(seed, options.salt ?? '', items.length, options.avoidOriginal ?? false);
|
|
306
|
+
return order.map((i) => items[i] as T);
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Inline formatting does not separate words; every other element boundary does. */
|
|
312
|
+
const INLINE_TEXT: ReadonlySet<string> = new Set([
|
|
313
|
+
'strong',
|
|
314
|
+
'em',
|
|
315
|
+
'b',
|
|
316
|
+
'i',
|
|
317
|
+
'u',
|
|
318
|
+
's',
|
|
319
|
+
'sub',
|
|
320
|
+
'sup',
|
|
321
|
+
'code',
|
|
322
|
+
'mark',
|
|
323
|
+
'span',
|
|
324
|
+
'a',
|
|
325
|
+
]);
|
|
326
|
+
|
|
327
|
+
function countWords(root: ElementNode): number {
|
|
328
|
+
const parts: string[] = [];
|
|
329
|
+
const walk = (node: Node): void => {
|
|
330
|
+
if (node.type === 'text') {
|
|
331
|
+
parts.push(node.value);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
const breaks = !INLINE_TEXT.has(node.tag);
|
|
335
|
+
if (breaks) parts.push(' ');
|
|
336
|
+
for (const child of node.children) walk(child);
|
|
337
|
+
if (breaks) parts.push(' ');
|
|
338
|
+
};
|
|
339
|
+
walk(root);
|
|
340
|
+
return parts
|
|
341
|
+
.join('')
|
|
342
|
+
.split(/\s+/u)
|
|
343
|
+
.filter((w) => /[\p{L}\p{N}]/u.test(w)).length;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function sortedRecord(entries: Iterable<[string, number]>): Record<string, number> {
|
|
347
|
+
const map = new Map<string, number>();
|
|
348
|
+
for (const [name, value] of entries) map.set(name, (map.get(name) ?? 0) + value);
|
|
349
|
+
const out: Record<string, number> = {};
|
|
350
|
+
for (const name of [...map.keys()].sort()) out[name] = round6(map.get(name) ?? 0);
|
|
351
|
+
return out;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function metadataOf(
|
|
355
|
+
doc: DocRecord,
|
|
356
|
+
root: ElementNode,
|
|
357
|
+
pageIds: readonly string[],
|
|
358
|
+
key: AnswerKey,
|
|
359
|
+
open: readonly string[],
|
|
360
|
+
): Metadata {
|
|
361
|
+
const { groups, viewHash } = key;
|
|
362
|
+
const slots = Object.values(key.slots);
|
|
363
|
+
const maxOf = (list: readonly ScoringGroup[]): number =>
|
|
364
|
+
round6(list.reduce((sum, g) => sum + groupMax(g.rule, g.points, g.slots.length), 0));
|
|
365
|
+
const pages: PageMetadata[] = doc.pages.map((p, i) => ({
|
|
366
|
+
id: pageIds[i] as string,
|
|
367
|
+
label: p.label,
|
|
368
|
+
slots: slots.filter((s) => s.page === pageIds[i]).length,
|
|
369
|
+
maxScore: maxOf(groups.filter((g) => g.page === pageIds[i])),
|
|
370
|
+
}));
|
|
371
|
+
const records = [...doc.components.values()];
|
|
372
|
+
const extra: [string, number][] = [];
|
|
373
|
+
for (const rec of records) {
|
|
374
|
+
const numbers = rec.definition.metadata?.(rec.element) ?? {};
|
|
375
|
+
for (const [name, value] of Object.entries(numbers)) {
|
|
376
|
+
if (Number.isFinite(value)) extra.push([`${rec.definition.manifest.tag}.${name}`, value]);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return {
|
|
380
|
+
format: FORMAT_VERSION,
|
|
381
|
+
lang: doc.lang,
|
|
382
|
+
dir: doc.dir,
|
|
383
|
+
...(doc.kind === DEFAULT_DOC_KIND ? {} : { kind: doc.kind }),
|
|
384
|
+
viewHash,
|
|
385
|
+
pages,
|
|
386
|
+
elements: sortedRecord(records.map((r) => [r.definition.manifest.tag, 1])),
|
|
387
|
+
slots: slots.length,
|
|
388
|
+
open,
|
|
389
|
+
groups: groups.length,
|
|
390
|
+
maxScore: maxOf(groups),
|
|
391
|
+
words: countWords(root),
|
|
392
|
+
extra: sortedRecord(extra),
|
|
393
|
+
};
|
|
394
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conformance helpers for fixture suites (pure, no file access): a leak probe for compiled views and a resolver from
|
|
3
|
+
* fixture refs to opaque ids.
|
|
4
|
+
*/
|
|
5
|
+
import { type ComponentManifest, type ElementNode, HELP_TAGS, type Node } from '@astl/core';
|
|
6
|
+
import { containsToken, descendants, findLeaks, wordsOf } from './guard.js';
|
|
7
|
+
import { parseHtml } from './html.js';
|
|
8
|
+
import { createHmac, elementPath, idMessage, opaqueId, secretBytes } from './ids.js';
|
|
9
|
+
|
|
10
|
+
export interface Leak {
|
|
11
|
+
/** Component tag. */
|
|
12
|
+
readonly tag: string;
|
|
13
|
+
/** Source id of the component, when known. */
|
|
14
|
+
readonly element: string | null;
|
|
15
|
+
/**
|
|
16
|
+
* - `value`: a private attribute value or private child text appears in the component's view element, or the text
|
|
17
|
+
* of a hint, an explanation or a feedback text appears in the view;
|
|
18
|
+
* - `attribute` / `child`: a private attribute or private child tag is present in the view, or a help element;
|
|
19
|
+
* - `structure`: source and view components do not line up.
|
|
20
|
+
*/
|
|
21
|
+
readonly kind: 'value' | 'attribute' | 'child' | 'structure';
|
|
22
|
+
readonly detail: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Component elements in document order, without recursion. */
|
|
26
|
+
function componentsOf(nodes: readonly Node[], tags: ReadonlySet<string>): ElementNode[] {
|
|
27
|
+
const out: ElementNode[] = [];
|
|
28
|
+
const stack: Node[] = [...nodes].reverse();
|
|
29
|
+
for (let node = stack.pop(); node !== undefined; node = stack.pop()) {
|
|
30
|
+
if (node.type !== 'element') continue;
|
|
31
|
+
if (tags.has(node.tag)) out.push(node);
|
|
32
|
+
else for (let i = node.children.length - 1; i >= 0; i--) stack.push(node.children[i] as Node);
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The nodes without help elements (and their content), recursively. */
|
|
38
|
+
function withoutHelp(nodes: readonly Node[]): Node[] {
|
|
39
|
+
return nodes.flatMap((n): Node[] =>
|
|
40
|
+
n.type === 'text' ? [n] : HELP_TAGS.has(n.tag) ? [] : [{ ...n, children: withoutHelp(n.children) }],
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Help is key data wherever it is (in an interaction or on a page): a view holds no help element, and none of their
|
|
46
|
+
* texts unless the author also wrote that text outside help.
|
|
47
|
+
*/
|
|
48
|
+
function helpLeaks(source: readonly Node[], view: readonly Node[]): Leak[] {
|
|
49
|
+
const leaks: Leak[] = [];
|
|
50
|
+
const all = (nodes: readonly Node[]) =>
|
|
51
|
+
nodes.flatMap((n) => (n.type === 'element' ? [n, ...descendants(n)] : []));
|
|
52
|
+
for (const el of all(view)) {
|
|
53
|
+
if (HELP_TAGS.has(el.tag)) leaks.push({ tag: el.tag, element: null, kind: 'child', detail: el.tag });
|
|
54
|
+
}
|
|
55
|
+
const viewText = wordsOf(view);
|
|
56
|
+
const outside = wordsOf(withoutHelp(source));
|
|
57
|
+
for (const el of all(source)) {
|
|
58
|
+
if (!HELP_TAGS.has(el.tag)) continue;
|
|
59
|
+
const text = wordsOf(el.children).trim();
|
|
60
|
+
if (text !== '' && containsToken(viewText, text) && !containsToken(outside, text)) {
|
|
61
|
+
leaks.push({ tag: el.tag, element: null, kind: 'value', detail: `${el.tag} "${text}"` });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return leaks;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Looks for answer data in a compiled view, with the same rules the compiler enforces (see `findLeaks` in the view
|
|
69
|
+
* guard): components are matched by document order; a leak is a private attribute or child present in the view, or
|
|
70
|
+
* a secret value (private strings, private child texts) found in the view's text or free-text attributes that the
|
|
71
|
+
* author did not also write in the element's public content. Help (hints, explanations, feedback texts) never
|
|
72
|
+
* reaches a view: a help element there is a leak, and so is the text of one the author did not also write outside it.
|
|
73
|
+
*/
|
|
74
|
+
export function leakProbe(source: string, view: string, manifests: readonly ComponentManifest[]): Leak[] {
|
|
75
|
+
const byTag = new Map(manifests.map((m) => [m.tag, m]));
|
|
76
|
+
const tags = new Set(byTag.keys());
|
|
77
|
+
const sourceNodes = parseHtml(source);
|
|
78
|
+
const viewNodes = parseHtml(view);
|
|
79
|
+
const sources = componentsOf(withoutHelp(sourceNodes), tags);
|
|
80
|
+
const views = componentsOf(viewNodes, tags);
|
|
81
|
+
const leaks: Leak[] = helpLeaks(sourceNodes, viewNodes);
|
|
82
|
+
if (sources.length !== views.length) {
|
|
83
|
+
const detail = `${sources.length} components in the source, ${views.length} in the view`;
|
|
84
|
+
leaks.push({ tag: '', element: null, kind: 'structure', detail });
|
|
85
|
+
}
|
|
86
|
+
for (let i = 0; i < Math.min(sources.length, views.length); i++) {
|
|
87
|
+
const src = sources[i] as ElementNode;
|
|
88
|
+
const out = views[i] as ElementNode;
|
|
89
|
+
const element = Object.hasOwn(src.attrs, 'id') ? (src.attrs.id ?? null) : null;
|
|
90
|
+
if (out.tag !== src.tag) {
|
|
91
|
+
leaks.push({ tag: src.tag, element, kind: 'structure', detail: `view has <${out.tag}> here` });
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
for (const found of findLeaks(src, out, byTag.get(src.tag) as ComponentManifest)) {
|
|
95
|
+
const detail = found.value === undefined ? found.what : `${found.what} "${found.value}"`;
|
|
96
|
+
leaks.push({ tag: src.tag, element, kind: found.kind, detail });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return leaks;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Maps a fixture ref to the opaque id the compiler gives it. */
|
|
103
|
+
export type RefResolver = (ref: string) => Promise<string>;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Resolves fixture refs for a secret and compile salt: `g1` (an element: its group or single slot), `q1/a` (a local
|
|
107
|
+
* id: an option or its flag slot), `page:p1` (a page) and `page:#0` (the implicit page).
|
|
108
|
+
*/
|
|
109
|
+
export function refResolver(secret: string | Uint8Array, salt = ''): RefResolver {
|
|
110
|
+
const hmac = createHmac(secretBytes(secret));
|
|
111
|
+
return async (ref) => {
|
|
112
|
+
const slash = ref.indexOf('/');
|
|
113
|
+
const path = ref.startsWith('page:')
|
|
114
|
+
? ref
|
|
115
|
+
: slash < 0
|
|
116
|
+
? elementPath(ref)
|
|
117
|
+
: elementPath(ref.slice(0, slash), ref.slice(slash + 1));
|
|
118
|
+
return opaqueId(await hmac(idMessage(salt, path)));
|
|
119
|
+
};
|
|
120
|
+
}
|