@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/engine.ts
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createEngine: the reference Engine (see `@astl/core` engine.ts). Options are checked eagerly, so a broken
|
|
3
|
+
* registration fails at start-up instead of on the first exercise.
|
|
4
|
+
*/
|
|
5
|
+
import {
|
|
6
|
+
allAttributes,
|
|
7
|
+
CLASS_ATTRIBUTE,
|
|
8
|
+
COLUMN_TAG,
|
|
9
|
+
COLUMNS_TAG,
|
|
10
|
+
CONTENT_ATTRIBUTES,
|
|
11
|
+
type CompileOptions,
|
|
12
|
+
type CompileResult,
|
|
13
|
+
type ComponentDefinition,
|
|
14
|
+
type ComponentManifest,
|
|
15
|
+
childTagConflict,
|
|
16
|
+
createI18n,
|
|
17
|
+
DEFAULT_PROFILE,
|
|
18
|
+
DOC_TAG,
|
|
19
|
+
ELEMENT_TAG_PATTERN,
|
|
20
|
+
type Engine,
|
|
21
|
+
type EngineOptions,
|
|
22
|
+
HELP_ATTRIBUTES,
|
|
23
|
+
HELP_TAGS,
|
|
24
|
+
isSafeUrl,
|
|
25
|
+
isStyleTemplate,
|
|
26
|
+
type NormalisationProfile,
|
|
27
|
+
PAGE_TAG,
|
|
28
|
+
SCORING_RULES,
|
|
29
|
+
type SlotKind,
|
|
30
|
+
STYLE_TAG,
|
|
31
|
+
STYLE_TEMPLATE_NAME,
|
|
32
|
+
type StyleTemplate,
|
|
33
|
+
strictUrlPolicy,
|
|
34
|
+
} from '@astl/core';
|
|
35
|
+
import { parseStyleColor } from '@astl/core/declarations';
|
|
36
|
+
import { analyse } from './analyse.js';
|
|
37
|
+
import { compileDocument } from './compile.js';
|
|
38
|
+
import { gradeKey, solutionOf } from './grade.js';
|
|
39
|
+
import { createHmac, secretBytes } from './ids.js';
|
|
40
|
+
import { engineMessages } from './messages.js';
|
|
41
|
+
import { BUILT_IN_SLOT_KINDS, isProfile } from './slot-kinds.js';
|
|
42
|
+
|
|
43
|
+
const MIN_SECRET_BYTES = 16;
|
|
44
|
+
const NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
45
|
+
const KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
46
|
+
/** Elements of the format itself, which no component can be. A child can share a tag: inside its host it wins. */
|
|
47
|
+
const FORMAT_TAGS: ReadonlySet<string> = new Set([DOC_TAG, PAGE_TAG, STYLE_TAG, COLUMNS_TAG, COLUMN_TAG]);
|
|
48
|
+
|
|
49
|
+
function checkManifest(manifest: ComponentManifest, slotKinds: ReadonlyMap<string, SlotKind>): void {
|
|
50
|
+
const tag = manifest.tag;
|
|
51
|
+
const bad = (why: string): never => {
|
|
52
|
+
throw new TypeError(`Component manifest ${tag}: ${why}`);
|
|
53
|
+
};
|
|
54
|
+
if (!ELEMENT_TAG_PATTERN.test(tag) || FORMAT_TAGS.has(tag)) {
|
|
55
|
+
bad('tag must be a lowercase custom element name');
|
|
56
|
+
}
|
|
57
|
+
if (!Number.isInteger(manifest.version) || manifest.version < 1) bad('version must be a positive integer');
|
|
58
|
+
if (manifest.display !== 'inline' && manifest.display !== 'block') bad('display must be inline or block');
|
|
59
|
+
if (manifest.content !== undefined && (manifest.content !== 'flow' || manifest.display !== 'block')) {
|
|
60
|
+
bad('content must be absent, or "flow" on a block');
|
|
61
|
+
}
|
|
62
|
+
if (manifest.graded !== (manifest.scoring !== null)) bad('graded types need scoring, ungraded types none');
|
|
63
|
+
if (manifest.variants !== null) {
|
|
64
|
+
const { default: fallback, values } = manifest.variants;
|
|
65
|
+
if (
|
|
66
|
+
values.length === 0 ||
|
|
67
|
+
new Set(values).size !== values.length ||
|
|
68
|
+
!values.every((v) => KEBAB.test(v))
|
|
69
|
+
) {
|
|
70
|
+
bad('variants must be distinct kebab-case names');
|
|
71
|
+
}
|
|
72
|
+
if (!values.includes(fallback)) bad(`variant default "${fallback}" is not one of its values`);
|
|
73
|
+
}
|
|
74
|
+
if (manifest.scoring !== null) {
|
|
75
|
+
const modes = manifest.scoring.modes;
|
|
76
|
+
if (!Object.hasOwn(modes, manifest.scoring.default)) {
|
|
77
|
+
bad(`scoring default "${manifest.scoring.default}" is not one of its modes`);
|
|
78
|
+
}
|
|
79
|
+
for (const rule of Object.values(modes))
|
|
80
|
+
if (!SCORING_RULES.includes(rule)) bad(`unknown scoring rule ${rule}`);
|
|
81
|
+
}
|
|
82
|
+
const checkAttributes = (list: readonly { readonly name: string }[], owner: string): void => {
|
|
83
|
+
const seen = new Set<string>();
|
|
84
|
+
for (const { name } of list) {
|
|
85
|
+
// `on*` would be an event handler in the view, whatever the manifest calls it.
|
|
86
|
+
if (
|
|
87
|
+
!NAME_PATTERN.test(name) ||
|
|
88
|
+
name.startsWith('on') ||
|
|
89
|
+
CONTENT_ATTRIBUTES.has(name) ||
|
|
90
|
+
HELP_ATTRIBUTES.includes(name) ||
|
|
91
|
+
name === CLASS_ATTRIBUTE ||
|
|
92
|
+
seen.has(name)
|
|
93
|
+
) {
|
|
94
|
+
bad(`attribute "${name}" of ${owner} is invalid, reserved or declared twice`);
|
|
95
|
+
}
|
|
96
|
+
seen.add(name);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
checkAttributes(allAttributes(manifest), tag);
|
|
100
|
+
const childTags = new Set<string>();
|
|
101
|
+
for (const child of manifest.children) {
|
|
102
|
+
if (
|
|
103
|
+
!ELEMENT_TAG_PATTERN.test(child.tag) ||
|
|
104
|
+
childTags.has(child.tag) ||
|
|
105
|
+
child.tag === tag ||
|
|
106
|
+
HELP_TAGS.has(child.tag)
|
|
107
|
+
) {
|
|
108
|
+
bad(`child tag "${child.tag}" is invalid, reserved or declared twice`);
|
|
109
|
+
}
|
|
110
|
+
if (!Number.isInteger(child.min) || child.min < 0 || (child.max !== null && child.max < child.min)) {
|
|
111
|
+
bad(`child ${child.tag} has an invalid min / max`);
|
|
112
|
+
}
|
|
113
|
+
if (child.place !== undefined && (child.place !== 'lead' || manifest.content !== 'flow')) {
|
|
114
|
+
bad(`child ${child.tag}: place must be absent, or "lead" in a type with content "flow"`);
|
|
115
|
+
}
|
|
116
|
+
childTags.add(child.tag);
|
|
117
|
+
checkAttributes(child.attributes, child.tag);
|
|
118
|
+
}
|
|
119
|
+
for (const name of manifest.slotKinds) {
|
|
120
|
+
const kind = slotKinds.get(name);
|
|
121
|
+
if (kind === undefined) bad(`slot kind "${name}" is not registered`);
|
|
122
|
+
else if ((kind.graded !== false) !== manifest.graded) {
|
|
123
|
+
bad(
|
|
124
|
+
manifest.graded
|
|
125
|
+
? `slot kind "${name}" is never graded: only ungraded types (graded: false) produce it`
|
|
126
|
+
: `slot kind "${name}" is graded: ungraded types produce only ungraded kinds such as open`,
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function resolveProfile(overrides: Partial<NormalisationProfile> = {}): NormalisationProfile {
|
|
133
|
+
const profile: NormalisationProfile = {
|
|
134
|
+
form: overrides.form ?? DEFAULT_PROFILE.form,
|
|
135
|
+
space: overrides.space ?? DEFAULT_PROFILE.space,
|
|
136
|
+
case: overrides.case ?? DEFAULT_PROFILE.case,
|
|
137
|
+
marks: overrides.marks ?? DEFAULT_PROFILE.marks,
|
|
138
|
+
punctuation: overrides.punctuation ?? DEFAULT_PROFILE.punctuation,
|
|
139
|
+
quotes: overrides.quotes ?? DEFAULT_PROFILE.quotes,
|
|
140
|
+
};
|
|
141
|
+
if (!isProfile(profile)) throw new TypeError('Engine profile has an unknown value');
|
|
142
|
+
return profile;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Style templates by name. The engine only reads names, scopes and component tags: looks are the player's job. */
|
|
146
|
+
function templateRegistry(templates: readonly StyleTemplate[]): ReadonlyMap<string, StyleTemplate> {
|
|
147
|
+
const byName = new Map<string, StyleTemplate>();
|
|
148
|
+
for (const template of templates) {
|
|
149
|
+
const name = String(template?.name);
|
|
150
|
+
if (!STYLE_TEMPLATE_NAME.test(name)) {
|
|
151
|
+
throw new TypeError(`Style template "${name}": the name must be lowercase kebab-case`);
|
|
152
|
+
}
|
|
153
|
+
if (!isStyleTemplate(template)) {
|
|
154
|
+
throw new TypeError(`Style template "${name}" needs a version, scopes, messages and string values`);
|
|
155
|
+
}
|
|
156
|
+
if (byName.has(template.name))
|
|
157
|
+
throw new TypeError(`Style template "${template.name}" is registered twice`);
|
|
158
|
+
byName.set(template.name, template);
|
|
159
|
+
}
|
|
160
|
+
return byName;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The secret's bytes, checked: a string or bytes, at least 16 bytes. */
|
|
164
|
+
function checkedSecret(secret: unknown): Uint8Array<ArrayBuffer> {
|
|
165
|
+
if (typeof secret !== 'string' && !(secret instanceof Uint8Array)) {
|
|
166
|
+
throw new TypeError('Engine secret must be a string or a Uint8Array');
|
|
167
|
+
}
|
|
168
|
+
const bytes = secretBytes(secret);
|
|
169
|
+
if (bytes.length < MIN_SECRET_BYTES)
|
|
170
|
+
throw new TypeError(`Engine secret must be at least ${MIN_SECRET_BYTES} bytes`);
|
|
171
|
+
return bytes;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Creates an engine. Throws a TypeError for a secret under 16 bytes, a tag, slot kind or style template registered
|
|
176
|
+
* twice, a manifest slot kind that is not registered, a child tag two manifests declare differently, or a manifest
|
|
177
|
+
* that fails its sanity checks. Without a secret it validates, grades, solves and describes, and `compile` throws a
|
|
178
|
+
* TypeError.
|
|
179
|
+
*/
|
|
180
|
+
export function createEngine(options: EngineOptions): Engine {
|
|
181
|
+
const secret = options.secret === undefined ? null : checkedSecret(options.secret);
|
|
182
|
+
|
|
183
|
+
const slotKinds = new Map<string, SlotKind>();
|
|
184
|
+
for (const kind of [...BUILT_IN_SLOT_KINDS, ...(options.slotKinds ?? [])]) {
|
|
185
|
+
if (slotKinds.has(kind.kind)) throw new TypeError(`Slot kind "${kind.kind}" is registered twice`);
|
|
186
|
+
if (kind.graded !== undefined && typeof kind.graded !== 'boolean') {
|
|
187
|
+
throw new TypeError(`Slot kind "${kind.kind}": graded must be a boolean`);
|
|
188
|
+
}
|
|
189
|
+
slotKinds.set(kind.kind, kind);
|
|
190
|
+
}
|
|
191
|
+
const definitions = new Map<string, ComponentDefinition>();
|
|
192
|
+
for (const definition of options.components) {
|
|
193
|
+
const tag = definition.manifest.tag;
|
|
194
|
+
if (definitions.has(tag)) throw new TypeError(`Component ${tag} is registered twice`);
|
|
195
|
+
checkManifest(definition.manifest, slotKinds);
|
|
196
|
+
definitions.set(tag, definition);
|
|
197
|
+
}
|
|
198
|
+
for (const definition of definitions.values()) {
|
|
199
|
+
for (const child of definition.manifest.children) {
|
|
200
|
+
if (definitions.has(child.tag)) {
|
|
201
|
+
throw new TypeError(
|
|
202
|
+
`Component manifest ${definition.manifest.tag}: child ${child.tag} is a component`,
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
// One child tag, one meaning: types share a child tag (`astl-prompt`) only with the same attributes and visibility.
|
|
208
|
+
const conflict = childTagConflict([...definitions.values()].map((d) => d.manifest));
|
|
209
|
+
if (conflict !== null) {
|
|
210
|
+
const [first, second] = conflict.components;
|
|
211
|
+
throw new TypeError(
|
|
212
|
+
`Component manifests ${first} and ${second} declare the child ${conflict.tag} differently: a shared child tag needs the same attributes and visibility`,
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const profile = resolveProfile(options.profile);
|
|
217
|
+
if (options.urlPolicy !== undefined && typeof options.urlPolicy !== 'function') {
|
|
218
|
+
throw new TypeError('urlPolicy must be a function');
|
|
219
|
+
}
|
|
220
|
+
const urlPolicy = strictUrlPolicy(options.urlPolicy ?? isSafeUrl);
|
|
221
|
+
const hmac = secret === null ? null : createHmac(secret);
|
|
222
|
+
const registered = [...definitions.values()];
|
|
223
|
+
const i18n = createI18n({
|
|
224
|
+
catalogs: [
|
|
225
|
+
...engineMessages,
|
|
226
|
+
...registered.flatMap((d) => d.messages ?? []),
|
|
227
|
+
...(options.catalogs ?? []),
|
|
228
|
+
],
|
|
229
|
+
});
|
|
230
|
+
const styleTemplates = templateRegistry(options.styleTemplates ?? []);
|
|
231
|
+
const { groundColors } = options;
|
|
232
|
+
if (
|
|
233
|
+
groundColors !== undefined &&
|
|
234
|
+
(parseStyleColor(groundColors.surface) === null || parseStyleColor(groundColors.ink) === null)
|
|
235
|
+
) {
|
|
236
|
+
throw new TypeError('groundColors must be colours written in hex or rgb()');
|
|
237
|
+
}
|
|
238
|
+
const analyseOptions = {
|
|
239
|
+
definitions,
|
|
240
|
+
urlPolicy,
|
|
241
|
+
profile,
|
|
242
|
+
styleTemplates,
|
|
243
|
+
...(groundColors === undefined ? {} : { groundColors }),
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
manifests: registered.map((d) => d.manifest),
|
|
248
|
+
validate(source) {
|
|
249
|
+
const { ok, issues } = analyse(source, analyseOptions);
|
|
250
|
+
return { ok, issues };
|
|
251
|
+
},
|
|
252
|
+
async compile(source: string, compileOptions: CompileOptions = {}): Promise<CompileResult> {
|
|
253
|
+
if (hmac === null) {
|
|
254
|
+
throw new TypeError(
|
|
255
|
+
'Engine secret is missing: compile needs createEngine({ secret }), at least 16 bytes',
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
const analysis = analyse(source, analyseOptions);
|
|
259
|
+
if (!analysis.ok || analysis.doc === null) return { ok: false, issues: analysis.issues };
|
|
260
|
+
const salt = compileOptions.salt ?? '';
|
|
261
|
+
const compilation = await compileDocument(analysis.doc, { hmac, salt, profile, slotKinds, urlPolicy });
|
|
262
|
+
return { ok: true, issues: analysis.issues, ...compilation };
|
|
263
|
+
},
|
|
264
|
+
grade(key, answers, gradeOptions = {}) {
|
|
265
|
+
return gradeKey(key, answers, gradeOptions, slotKinds);
|
|
266
|
+
},
|
|
267
|
+
solution(key, gradeOptions = {}) {
|
|
268
|
+
return solutionOf(key, gradeOptions, slotKinds);
|
|
269
|
+
},
|
|
270
|
+
describe(issue, locale) {
|
|
271
|
+
return i18n.t(locale, issue.namespace, issue.code, issue.params);
|
|
272
|
+
},
|
|
273
|
+
};
|
|
274
|
+
}
|
package/src/grade.ts
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Grading: pure and synchronous. Answers are untrusted (malformed = unanswered); a malformed key is a host error and
|
|
3
|
+
* throws a TypeError.
|
|
4
|
+
*/
|
|
5
|
+
import {
|
|
6
|
+
type AnswerKey,
|
|
7
|
+
type Answers,
|
|
8
|
+
FLAG_SELECTED,
|
|
9
|
+
fitsAnswer,
|
|
10
|
+
type GradeOptions,
|
|
11
|
+
type GradeResult,
|
|
12
|
+
type GroupResult,
|
|
13
|
+
type GroupVerdict,
|
|
14
|
+
groupMax,
|
|
15
|
+
isAnswerKey,
|
|
16
|
+
type KeySlot,
|
|
17
|
+
SCORING_RULES,
|
|
18
|
+
type Score,
|
|
19
|
+
type ScoringGroup,
|
|
20
|
+
type SlotKind,
|
|
21
|
+
type SlotVerdict,
|
|
22
|
+
type Solution,
|
|
23
|
+
} from '@astl/core';
|
|
24
|
+
import { round6 } from './round.js';
|
|
25
|
+
|
|
26
|
+
export type SlotKinds = ReadonlyMap<string, SlotKind>;
|
|
27
|
+
|
|
28
|
+
function assertKey(key: AnswerKey): void {
|
|
29
|
+
const valid =
|
|
30
|
+
isAnswerKey(key) &&
|
|
31
|
+
key.pages.every((p) => typeof p === 'string') &&
|
|
32
|
+
key.groups.every(
|
|
33
|
+
(g: Partial<ScoringGroup>) =>
|
|
34
|
+
typeof g === 'object' &&
|
|
35
|
+
g !== null &&
|
|
36
|
+
typeof g.id === 'string' &&
|
|
37
|
+
typeof g.page === 'string' &&
|
|
38
|
+
SCORING_RULES.includes(g.rule as ScoringGroup['rule']) &&
|
|
39
|
+
typeof g.points === 'number' &&
|
|
40
|
+
Number.isFinite(g.points) &&
|
|
41
|
+
g.points >= 0 &&
|
|
42
|
+
Array.isArray(g.slots) &&
|
|
43
|
+
g.slots.every((s) => typeof s === 'string'),
|
|
44
|
+
);
|
|
45
|
+
if (!valid) throw new TypeError('Invalid answer key');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function slotOf(key: AnswerKey, id: string, kinds: SlotKinds): { slot: KeySlot; kind: SlotKind } {
|
|
49
|
+
const slot = Object.hasOwn(key.slots, id) ? key.slots[id] : undefined;
|
|
50
|
+
if (slot === undefined) throw new TypeError(`Invalid answer key: unknown slot ${id}`);
|
|
51
|
+
const kind = kinds.get(slot.kind);
|
|
52
|
+
if (kind === undefined)
|
|
53
|
+
throw new TypeError(`Invalid answer key: slot kind "${slot.kind}" is not registered`);
|
|
54
|
+
// Only group slots get here: an open slot (an ungraded kind) is stored for the teacher and belongs to no group.
|
|
55
|
+
if (kind.graded === false)
|
|
56
|
+
throw new TypeError(`Invalid answer key: slot ${id} is of the ungraded kind "${slot.kind}"`);
|
|
57
|
+
if (typeof slot.key !== 'object' || slot.key === null || !kind.isKey(slot.key)) {
|
|
58
|
+
throw new TypeError(`Invalid answer key: slot ${id} has an invalid ${slot.kind} key`);
|
|
59
|
+
}
|
|
60
|
+
return { slot, kind };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The answer for a slot, or null when it is unanswered (missing, not a string, empty or longer than its kind allows,
|
|
65
|
+
* in code points).
|
|
66
|
+
*/
|
|
67
|
+
function answerOf(answers: object, id: string, kind: string): string | null {
|
|
68
|
+
const value: unknown = Object.hasOwn(answers, id) ? (answers as Record<string, unknown>)[id] : undefined;
|
|
69
|
+
return typeof value === 'string' && value !== '' && fitsAnswer(value, kind) ? value : null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The view element a group belongs to: the component of its slots (`KeySlot.group`). */
|
|
73
|
+
function elementOf(key: AnswerKey, group: ScoringGroup): string | undefined {
|
|
74
|
+
const first = group.slots[0];
|
|
75
|
+
return first !== undefined && Object.hasOwn(key.slots, first) ? key.slots[first]?.group : undefined;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function groupsFor(key: AnswerKey, options: GradeOptions): readonly ScoringGroup[] {
|
|
79
|
+
const { page, element } = options;
|
|
80
|
+
return key.groups.filter(
|
|
81
|
+
(g) =>
|
|
82
|
+
(page === undefined || g.page === page) && (element === undefined || elementOf(key, g) === element),
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The fraction of its maximum each group loses for the hints used (`GradeOptions.hintsUsed`): the costs of the first
|
|
88
|
+
* n hints of its element and of its page. Counts that are not positive integers use nothing.
|
|
89
|
+
*/
|
|
90
|
+
function hintCosts(key: AnswerKey, used: Readonly<Record<string, number>>): (group: ScoringGroup) => number {
|
|
91
|
+
const spent = (id: string | undefined): number => {
|
|
92
|
+
if (id === undefined || !Object.hasOwn(used, id)) return 0;
|
|
93
|
+
const n = used[id];
|
|
94
|
+
if (typeof n !== 'number' || !Number.isInteger(n) || n <= 0) return 0;
|
|
95
|
+
const hints = key.help !== undefined && Object.hasOwn(key.help, id) ? key.help[id]?.hints : undefined;
|
|
96
|
+
if (hints === undefined) return 0;
|
|
97
|
+
if (!Array.isArray(hints) || !hints.every((h) => isCost((h as { cost?: unknown })?.cost))) {
|
|
98
|
+
throw new TypeError(`Invalid answer key: the hints of ${id} have invalid costs`);
|
|
99
|
+
}
|
|
100
|
+
return hints.slice(0, n).reduce((sum, h) => sum + h.cost, 0);
|
|
101
|
+
};
|
|
102
|
+
return (group) => spent(elementOf(key, group)) + spent(group.page);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const isCost = (x: unknown): x is number => typeof x === 'number' && x >= 0 && x <= 1;
|
|
106
|
+
|
|
107
|
+
interface GroupOutcome {
|
|
108
|
+
readonly result: GroupResult;
|
|
109
|
+
readonly visible: Readonly<Record<string, SlotVerdict>>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function gradeGroup(group: ScoringGroup, key: AnswerKey, answers: object, kinds: SlotKinds): GroupOutcome {
|
|
113
|
+
const n = group.slots.length;
|
|
114
|
+
let answered = 0;
|
|
115
|
+
let correct = 0;
|
|
116
|
+
const outcomes: { id: string; answered: boolean; correct: boolean }[] = [];
|
|
117
|
+
for (const id of group.slots) {
|
|
118
|
+
const { slot, kind } = slotOf(key, id, kinds);
|
|
119
|
+
const lang = typeof slot.key.lang === 'string' ? slot.key.lang : key.lang;
|
|
120
|
+
const answer = answerOf(answers, id, slot.kind);
|
|
121
|
+
let isAnswered: boolean;
|
|
122
|
+
let isCorrect: boolean;
|
|
123
|
+
if (kind.selection) {
|
|
124
|
+
// Selection slots: an unselected flag is right when it should stay unselected.
|
|
125
|
+
isAnswered = answer === FLAG_SELECTED;
|
|
126
|
+
isCorrect = isAnswered === kind.isCorrect(slot.key, FLAG_SELECTED, { lang });
|
|
127
|
+
} else {
|
|
128
|
+
isAnswered = answer !== null;
|
|
129
|
+
isCorrect = answer !== null && kind.isCorrect(slot.key, answer, { lang });
|
|
130
|
+
}
|
|
131
|
+
if (isAnswered) answered++;
|
|
132
|
+
if (isCorrect) correct++;
|
|
133
|
+
outcomes.push({ id, answered: isAnswered, correct: isCorrect });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const points = group.points;
|
|
137
|
+
const max = groupMax(group.rule, points, n);
|
|
138
|
+
let score = 0;
|
|
139
|
+
let verdict: GroupVerdict;
|
|
140
|
+
if (answered === 0) {
|
|
141
|
+
verdict = 'empty';
|
|
142
|
+
} else {
|
|
143
|
+
const all = correct === n;
|
|
144
|
+
if (group.rule === 'all-correct') {
|
|
145
|
+
score = all ? points : 0;
|
|
146
|
+
verdict = all ? 'correct' : 'incorrect';
|
|
147
|
+
} else {
|
|
148
|
+
score = group.rule === 'per-slot' ? points * correct : (points * correct) / n;
|
|
149
|
+
verdict = all ? 'correct' : correct === 0 ? 'incorrect' : 'partial';
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const visible: Record<string, SlotVerdict> = {};
|
|
154
|
+
// Multi-slot all-correct groups show only the group verdict, never which slot is wrong.
|
|
155
|
+
if (verdict !== 'empty' && !(group.rule === 'all-correct' && n > 1)) {
|
|
156
|
+
for (const o of outcomes) if (o.answered) visible[o.id] = o.correct ? 'correct' : 'incorrect';
|
|
157
|
+
}
|
|
158
|
+
return { result: { id: group.id, verdict, score, max }, visible };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function gradeKey(
|
|
162
|
+
key: AnswerKey,
|
|
163
|
+
answers: Answers,
|
|
164
|
+
options: GradeOptions,
|
|
165
|
+
kinds: SlotKinds,
|
|
166
|
+
): GradeResult {
|
|
167
|
+
assertKey(key);
|
|
168
|
+
const input: object = typeof answers === 'object' && answers !== null ? answers : {};
|
|
169
|
+
const groups = groupsFor(key, options);
|
|
170
|
+
// A check of one element reports its page's score of that element only.
|
|
171
|
+
const graded = new Set(groups.map((g) => g.page));
|
|
172
|
+
const pageIds =
|
|
173
|
+
options.element !== undefined
|
|
174
|
+
? key.pages.filter((p) => graded.has(p))
|
|
175
|
+
: options.page === undefined
|
|
176
|
+
? key.pages
|
|
177
|
+
: key.pages.filter((p) => p === options.page);
|
|
178
|
+
const costOf = options.hintsUsed === undefined ? null : hintCosts(key, options.hintsUsed);
|
|
179
|
+
const pageTotals = new Map<string, { score: number; max: number }>(
|
|
180
|
+
pageIds.map((p) => [p, { score: 0, max: 0 }]),
|
|
181
|
+
);
|
|
182
|
+
const slots: Record<string, SlotVerdict> = {};
|
|
183
|
+
const results: GroupResult[] = [];
|
|
184
|
+
const counts = { correct: 0, partial: 0, incorrect: 0, empty: 0 };
|
|
185
|
+
let score = 0;
|
|
186
|
+
let max = 0;
|
|
187
|
+
for (const group of groups) {
|
|
188
|
+
const outcome = gradeGroup(group, key, input, kinds);
|
|
189
|
+
const cost = costOf?.(group) ?? 0;
|
|
190
|
+
// Hints lower the score, never the verdict: the answer is still right.
|
|
191
|
+
const lowered = round6(Math.max(0, outcome.result.score - cost * outcome.result.max));
|
|
192
|
+
const result = cost > 0 ? { ...outcome.result, score: lowered } : outcome.result;
|
|
193
|
+
const visible = outcome.visible;
|
|
194
|
+
results.push(result);
|
|
195
|
+
Object.assign(slots, visible);
|
|
196
|
+
counts[result.verdict]++;
|
|
197
|
+
score += result.score;
|
|
198
|
+
max += result.max;
|
|
199
|
+
const total = pageTotals.get(group.page);
|
|
200
|
+
if (total !== undefined) {
|
|
201
|
+
total.score += result.score;
|
|
202
|
+
total.max += result.max;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const pages: Record<string, Score> = {};
|
|
206
|
+
for (const [id, total] of pageTotals) pages[id] = { score: round6(total.score), max: round6(total.max) };
|
|
207
|
+
return {
|
|
208
|
+
score: round6(score),
|
|
209
|
+
max: round6(max),
|
|
210
|
+
correct: groups.length > 0 && counts.correct === groups.length,
|
|
211
|
+
slots,
|
|
212
|
+
groups: results,
|
|
213
|
+
pages,
|
|
214
|
+
counts: { ...counts, total: groups.length },
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function solutionOf(key: AnswerKey, options: GradeOptions, kinds: SlotKinds): Solution {
|
|
219
|
+
assertKey(key);
|
|
220
|
+
const out: Record<string, string> = {};
|
|
221
|
+
for (const group of groupsFor(key, options)) {
|
|
222
|
+
for (const id of group.slots) {
|
|
223
|
+
const { slot, kind } = slotOf(key, id, kinds);
|
|
224
|
+
const value = kind.solution(slot.key);
|
|
225
|
+
if (value !== '') out[id] = value;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return out;
|
|
229
|
+
}
|