@astl/core 0.0.0 → 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.
Files changed (139) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/LICENSE +202 -0
  3. package/README.md +38 -0
  4. package/dist/answers.d.ts +29 -0
  5. package/dist/answers.d.ts.map +1 -0
  6. package/dist/answers.js +40 -0
  7. package/dist/answers.js.map +1 -0
  8. package/dist/ast.d.ts +25 -0
  9. package/dist/ast.d.ts.map +1 -0
  10. package/dist/ast.js +27 -0
  11. package/dist/ast.js.map +1 -0
  12. package/dist/authoring.d.ts +451 -0
  13. package/dist/authoring.d.ts.map +1 -0
  14. package/dist/authoring.js +2 -0
  15. package/dist/authoring.js.map +1 -0
  16. package/dist/checker.d.ts +78 -0
  17. package/dist/checker.d.ts.map +1 -0
  18. package/dist/checker.js +10 -0
  19. package/dist/checker.js.map +1 -0
  20. package/dist/compiled.d.ts +94 -0
  21. package/dist/compiled.d.ts.map +1 -0
  22. package/dist/compiled.js +16 -0
  23. package/dist/compiled.js.map +1 -0
  24. package/dist/content.d.ts +72 -0
  25. package/dist/content.d.ts.map +1 -0
  26. package/dist/content.js +128 -0
  27. package/dist/content.js.map +1 -0
  28. package/dist/declarations.d.ts +52 -0
  29. package/dist/declarations.d.ts.map +1 -0
  30. package/dist/declarations.js +358 -0
  31. package/dist/declarations.js.map +1 -0
  32. package/dist/definition.d.ts +106 -0
  33. package/dist/definition.d.ts.map +1 -0
  34. package/dist/definition.js +2 -0
  35. package/dist/definition.js.map +1 -0
  36. package/dist/engine.d.ts +95 -0
  37. package/dist/engine.d.ts.map +1 -0
  38. package/dist/engine.js +2 -0
  39. package/dist/engine.js.map +1 -0
  40. package/dist/format.d.ts +29 -0
  41. package/dist/format.d.ts.map +1 -0
  42. package/dist/format.js +55 -0
  43. package/dist/format.js.map +1 -0
  44. package/dist/help.d.ts +38 -0
  45. package/dist/help.d.ts.map +1 -0
  46. package/dist/help.js +22 -0
  47. package/dist/help.js.map +1 -0
  48. package/dist/i18n/check.d.ts +11 -0
  49. package/dist/i18n/check.d.ts.map +1 -0
  50. package/dist/i18n/check.js +64 -0
  51. package/dist/i18n/check.js.map +1 -0
  52. package/dist/i18n/format.d.ts +40 -0
  53. package/dist/i18n/format.d.ts.map +1 -0
  54. package/dist/i18n/format.js +280 -0
  55. package/dist/i18n/format.js.map +1 -0
  56. package/dist/i18n/i18n.d.ts +14 -0
  57. package/dist/i18n/i18n.d.ts.map +1 -0
  58. package/dist/i18n/i18n.js +82 -0
  59. package/dist/i18n/i18n.js.map +1 -0
  60. package/dist/i18n/types.d.ts +31 -0
  61. package/dist/i18n/types.d.ts.map +1 -0
  62. package/dist/i18n/types.js +7 -0
  63. package/dist/i18n/types.js.map +1 -0
  64. package/dist/index.d.ts +45 -0
  65. package/dist/index.d.ts.map +1 -0
  66. package/dist/index.js +21 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/issues.d.ts +98 -0
  69. package/dist/issues.d.ts.map +1 -0
  70. package/dist/issues.js +74 -0
  71. package/dist/issues.js.map +1 -0
  72. package/dist/json.d.ts +7 -0
  73. package/dist/json.d.ts.map +1 -0
  74. package/dist/json.js +2 -0
  75. package/dist/json.js.map +1 -0
  76. package/dist/manifest.d.ts +135 -0
  77. package/dist/manifest.d.ts.map +1 -0
  78. package/dist/manifest.js +63 -0
  79. package/dist/manifest.js.map +1 -0
  80. package/dist/player.d.ts +129 -0
  81. package/dist/player.d.ts.map +1 -0
  82. package/dist/player.js +18 -0
  83. package/dist/player.js.map +1 -0
  84. package/dist/policy.d.ts +53 -0
  85. package/dist/policy.d.ts.map +1 -0
  86. package/dist/policy.js +55 -0
  87. package/dist/policy.js.map +1 -0
  88. package/dist/protocol.d.ts +54 -0
  89. package/dist/protocol.d.ts.map +1 -0
  90. package/dist/protocol.js +51 -0
  91. package/dist/protocol.js.map +1 -0
  92. package/dist/result.d.ts +44 -0
  93. package/dist/result.d.ts.map +1 -0
  94. package/dist/result.js +5 -0
  95. package/dist/result.js.map +1 -0
  96. package/dist/scoring.d.ts +27 -0
  97. package/dist/scoring.d.ts.map +1 -0
  98. package/dist/scoring.js +6 -0
  99. package/dist/scoring.js.map +1 -0
  100. package/dist/slots.d.ts +47 -0
  101. package/dist/slots.d.ts.map +1 -0
  102. package/dist/slots.js +9 -0
  103. package/dist/slots.js.map +1 -0
  104. package/dist/snapshot.d.ts +23 -0
  105. package/dist/snapshot.d.ts.map +1 -0
  106. package/dist/snapshot.js +22 -0
  107. package/dist/snapshot.js.map +1 -0
  108. package/dist/style.d.ts +51 -0
  109. package/dist/style.d.ts.map +1 -0
  110. package/dist/style.js +36 -0
  111. package/dist/style.js.map +1 -0
  112. package/package.json +40 -4
  113. package/src/answers.ts +52 -0
  114. package/src/ast.ts +49 -0
  115. package/src/authoring.ts +475 -0
  116. package/src/checker.ts +91 -0
  117. package/src/compiled.ts +115 -0
  118. package/src/content.ts +156 -0
  119. package/src/declarations.ts +427 -0
  120. package/src/definition.ts +104 -0
  121. package/src/engine.ts +98 -0
  122. package/src/format.ts +67 -0
  123. package/src/help.ts +41 -0
  124. package/src/i18n/check.ts +67 -0
  125. package/src/i18n/format.ts +318 -0
  126. package/src/i18n/i18n.ts +92 -0
  127. package/src/i18n/types.ts +35 -0
  128. package/src/index.ts +201 -0
  129. package/src/issues.ts +107 -0
  130. package/src/json.ts +6 -0
  131. package/src/manifest.ts +193 -0
  132. package/src/player.ts +145 -0
  133. package/src/policy.ts +117 -0
  134. package/src/protocol.ts +65 -0
  135. package/src/result.ts +53 -0
  136. package/src/scoring.ts +31 -0
  137. package/src/slots.ts +57 -0
  138. package/src/snapshot.ts +40 -0
  139. package/src/style.ts +89 -0
package/src/content.ts ADDED
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The rich-text allow-list of content format 1, shared by the engine (sanitiser, view guard) and the player
3
+ * (defensive pass when mounting a view). One list, so both sides can never disagree.
4
+ */
5
+ import type { UrlPolicy } from './engine.js';
6
+
7
+ export const BLOCK_TAGS: ReadonlySet<string> = new Set([
8
+ 'p',
9
+ 'h2',
10
+ 'h3',
11
+ 'h4',
12
+ 'ul',
13
+ 'ol',
14
+ 'li',
15
+ 'blockquote',
16
+ ]);
17
+
18
+ /** `img` is a picture: inline, so it can sit in text, prompts, options and cards. */
19
+ export const INLINE_TAGS: ReadonlySet<string> = new Set([
20
+ 'strong',
21
+ 'em',
22
+ 'b',
23
+ 'i',
24
+ 'u',
25
+ 's',
26
+ 'sub',
27
+ 'sup',
28
+ 'code',
29
+ 'mark',
30
+ 'span',
31
+ 'a',
32
+ 'br',
33
+ 'img',
34
+ ]);
35
+
36
+ /**
37
+ * A picture with a caption: a block directly in a page (or the document), holding exactly one `img` and at most one
38
+ * `figcaption` (rich inline text), nothing else. A `figcaption` anywhere else is unwrapped.
39
+ */
40
+ export const FIGURE_TAG = 'figure';
41
+ export const CAPTION_TAG = 'figcaption';
42
+
43
+ /** Dropped together with their content: active content, embeds, media and form controls. */
44
+ export const REMOVED_WITH_CONTENT: ReadonlySet<string> = new Set([
45
+ 'script',
46
+ 'style',
47
+ 'template',
48
+ 'iframe',
49
+ 'object',
50
+ 'embed',
51
+ 'noscript',
52
+ 'svg',
53
+ 'math',
54
+ 'video',
55
+ 'audio',
56
+ 'form',
57
+ 'input',
58
+ 'select',
59
+ 'textarea',
60
+ 'button',
61
+ ]);
62
+
63
+ /**
64
+ * Attributes allowed on every content element. `style` goes through the allow-list of `declarations.ts` at each side
65
+ * that reads it. `class` is not here on purpose: it exists in sources only, and the engine inlines it.
66
+ */
67
+ export const CONTENT_ATTRIBUTES: ReadonlySet<string> = new Set(['lang', 'dir', 'style']);
68
+
69
+ /** A source attribute naming named styles (`<astl-style name>`); no view ever holds it. */
70
+ export const CLASS_ATTRIBUTE = 'class';
71
+
72
+ /** What `inertStyles` renames `style` to. */
73
+ export const INERT_STYLE = 'data-astl-style';
74
+
75
+ const START_TAG = /<[a-z](?:[^<>"']|"[^"]*"|'[^']*')*>/gi;
76
+ const STYLE_IN_TAG = /"[^"]*"|'[^']*'|(\s)style\s*=/gi;
77
+
78
+ /**
79
+ * The HTML with every `style` attribute under another name, for parsing. Under a strict CSP any HTML parser reports a
80
+ * `style` attribute as a violation the moment it meets one, in a template or a DOMParser document too (seen in Chromium
81
+ * on all of them), though nothing in those documents is ever drawn. Only start tags change, never text or values.
82
+ */
83
+ export const inertStyles = (html: string): string =>
84
+ html.replace(START_TAG, (tag) =>
85
+ tag.replace(STYLE_IN_TAG, (found, space?: string) =>
86
+ space === undefined ? found : `${space}${INERT_STYLE}=`,
87
+ ),
88
+ );
89
+
90
+ /**
91
+ * A rule, first in `<astl-doc>`: `name` and `label` (a named style, applied with `class`) or `for` (every element of
92
+ * that tag), with its declarations in `style`. Sources only: the engine inlines it.
93
+ */
94
+ export const STYLE_TAG = 'astl-style';
95
+
96
+ /** A layout: 2 to 4 columns directly on a page or in the document, wrapping by themselves; no nesting. */
97
+ export const COLUMNS_TAG = 'astl-columns';
98
+ /** One column of a layout: blocks, figures and block components, as a page holds them. */
99
+ export const COLUMN_TAG = 'astl-column';
100
+ export const MIN_COLUMNS = 2;
101
+ export const MAX_COLUMNS = 4;
102
+
103
+ /**
104
+ * Extra attributes allowed on specific rich-text elements. A picture: `src` and `alt` (required; `alt=""` marks
105
+ * decoration), `width` and `height` (positive integers, so the layout does not jump while it loads).
106
+ */
107
+ export const TAG_ATTRIBUTES: Readonly<Record<string, readonly string[]>> = {
108
+ a: ['href'],
109
+ ol: ['start'],
110
+ img: ['src', 'alt', 'width', 'height'],
111
+ };
112
+
113
+ /** The attribute of a rich-text element that holds a URL, checked by the URL policy. */
114
+ export const URL_ATTRIBUTES: Readonly<Record<string, string>> = { a: 'href', img: 'src' };
115
+
116
+ /** Attributes the document and page elements may carry in a view. */
117
+ export const DOC_ATTRIBUTES: readonly string[] = ['format', 'lang', 'dir', 'kind', 'style', 'style-template'];
118
+
119
+ /**
120
+ * What a document is, its `kind`: how it shows, never how it grades. An `exercise` (the default when absent) shows one
121
+ * page at a time; a `book` shows two pages side by side (1-2, 3-4, ...) where the player is wide enough, turning them
122
+ * a spread at a time. Practice and test are not kinds: they are policies over any kind (policy.ts).
123
+ */
124
+ export const DOC_KINDS = ['exercise', 'book'] as const;
125
+ export type DocKind = (typeof DOC_KINDS)[number];
126
+ export const DEFAULT_DOC_KIND: DocKind = 'exercise';
127
+ export const PAGE_ATTRIBUTES: readonly string[] = ['id', 'label', 'lang', 'dir', 'style'];
128
+
129
+ /** Most attributes one element may carry in a source (beyond it: SOURCE_TOO_COMPLEX, checked before parsing). */
130
+ export const MAX_ATTRIBUTES_PER_ELEMENT = 256;
131
+
132
+ /** Deepest element nesting a source may have (beyond it: SOURCE_TOO_DEEP). */
133
+ export const MAX_NESTING_DEPTH = 100;
134
+
135
+ const SAFE_SCHEMES: ReadonlySet<string> = new Set(['http', 'https', 'mailto']);
136
+
137
+ /** The default URL policy: absolute `http:`, `https:` and `mailto:` URLs (tabs and newlines ignored, as browsers do). */
138
+ export function isSafeUrl(url: string): boolean {
139
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(url.replace(/[\t\n\r]/g, '').trim());
140
+ return scheme !== null && SAFE_SCHEMES.has((scheme[1] ?? '').toLowerCase());
141
+ }
142
+
143
+ /**
144
+ * A host's URL policy as engines, players and the authoring kit use it: a URL passes only when the policy returns
145
+ * `true`. A policy that throws, or returns anything else (the Promise of an async function, say), blocks the URL.
146
+ */
147
+ export function strictUrlPolicy(policy: UrlPolicy): UrlPolicy {
148
+ if (policy === isSafeUrl) return isSafeUrl;
149
+ return (url, context) => {
150
+ try {
151
+ return policy(url, context) === true;
152
+ } catch {
153
+ return false;
154
+ }
155
+ };
156
+ }
@@ -0,0 +1,427 @@
1
+ /**
2
+ * The `style` allow-list of content format 1: which properties an author may set and what each may hold, value by
3
+ * value. The output is rebuilt from validated tokens only, so whatever a style hides (comments, escapes, `!important`,
4
+ * an unclosed parenthesis) never reaches a browser. Exercises play on public pages: nothing here can leave its box,
5
+ * cover other content, load anything or hide text.
6
+ *
7
+ * `@astl/core/declarations`, not in the main entry: every bundle re-exports that one, so this table would load with every
8
+ * player, and it is needed only by exercises that use styles.
9
+ */
10
+
11
+ /** Longest `style` value read; a longer one is dropped whole. */
12
+ export const MAX_STYLE_LENGTH = 2000;
13
+ /** Most `<astl-style>` rules a document may have. */
14
+ export const MAX_STYLE_RULES = 100;
15
+ /** Most characters of `style` inlining may write in one view: rules are short, the elements they reach may be many. */
16
+ export const MAX_INLINED_STYLES = 1_000_000;
17
+
18
+ /** `name` of a named style, the only classes that exist: never one of the editing surface's own. */
19
+ const STYLE_NAME = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
20
+ const RESERVED_NAME = /^(?:astl-|tiptap|prosemirror)/i;
21
+
22
+ /** Whether `name` can name a style: the grammar, and none of the reserved prefixes `astl-`, `tiptap`, `prosemirror`. */
23
+ export function isStyleName(name: string): boolean {
24
+ return STYLE_NAME.test(name) && !RESERVED_NAME.test(name);
25
+ }
26
+
27
+ /** A `class` value as an editing surface keeps it: the tokens that can name a style, each once. */
28
+ export function cleanClass(value: string): string {
29
+ return [...new Set(value.split(/\s+/).filter(isStyleName))].join(' ');
30
+ }
31
+
32
+ /** One kept declaration: lowercase property, normalised value. */
33
+ export type StyleDeclaration = readonly [name: string, value: string];
34
+
35
+ export interface CleanedStyle {
36
+ /** The kept declarations as a `style` value: `name: value; name: value`, empty when none is left. */
37
+ readonly style: string;
38
+ readonly declarations: readonly StyleDeclaration[];
39
+ /** The property names refused, in order; for what is not a declaration at all, its first characters. */
40
+ readonly removed: readonly string[];
41
+ }
42
+
43
+ /** Red, green and blue (0 to 255) and alpha (0 to 1). */
44
+ export type StyleColor = readonly [red: number, green: number, blue: number, alpha: number];
45
+
46
+ /** Checks a lowercase value (font names keep their case) and returns its normal form, or null to refuse it. */
47
+ type Kind = (value: string) => string | null;
48
+
49
+ /** `text` split at `separator` (a space stands for any white space) outside parentheses and quotes. */
50
+ function splitTop(text: string, separator: ';' | ',' | ' '): string[] {
51
+ const parts: string[] = [];
52
+ let depth = 0;
53
+ let quote = '';
54
+ let start = 0;
55
+ for (let i = 0; i < text.length; i++) {
56
+ const c = text.charAt(i);
57
+ if (quote !== '') {
58
+ if (c === quote) quote = '';
59
+ } else if (c === '"' || c === "'") quote = c;
60
+ else if (c === '(') depth++;
61
+ else if (c === ')') depth--;
62
+ else if (depth === 0 && (c === separator || (separator === ' ' && /\s/.test(c)))) {
63
+ parts.push(text.slice(start, i));
64
+ start = i + 1;
65
+ }
66
+ }
67
+ parts.push(text.slice(start));
68
+ return parts.map((part) => part.trim()).filter((part) => part !== '');
69
+ }
70
+
71
+ const words =
72
+ (...allowed: readonly string[]): Kind =>
73
+ (value) =>
74
+ allowed.includes(value) ? value : null;
75
+
76
+ const either =
77
+ (...kinds: readonly Kind[]): Kind =>
78
+ (value) => {
79
+ for (const kind of kinds) {
80
+ const kept = kind(value);
81
+ if (kept !== null) return kept;
82
+ }
83
+ return null;
84
+ };
85
+
86
+ /** One to `max` space-separated values. */
87
+ const upTo =
88
+ (max: number, kind: Kind): Kind =>
89
+ (value) => {
90
+ const parts = splitTop(value, ' ');
91
+ if (parts.length === 0 || parts.length > max) return null;
92
+ const kept = parts.map(kind);
93
+ return kept.includes(null) ? null : kept.join(' ');
94
+ };
95
+
96
+ /** Values of the kinds given, in any order, each kind at most once: the shape of `border` and its like. */
97
+ const anyOrder =
98
+ (...kinds: readonly Kind[]): Kind =>
99
+ (value) => {
100
+ const free = [...kinds];
101
+ const parts = splitTop(value, ' ');
102
+ if (parts.length === 0) return null;
103
+ const kept: string[] = [];
104
+ for (const part of parts) {
105
+ const index = free.findIndex((kind) => kind(part) !== null);
106
+ if (index < 0) return null;
107
+ kept.push((free[index] as Kind)(part) as string);
108
+ free.splice(index, 1);
109
+ }
110
+ return kept.join(' ');
111
+ };
112
+
113
+ const NUMBER = /^\d{1,6}(?:\.\d{1,6})?$|^\.\d{1,6}$/;
114
+ const DIMENSION = /^(\d{1,6}(?:\.\d{1,6})?|\.\d{1,6})(px|pt|em|rem|%)?$/;
115
+ /** What a length comes to, for its bound: 1em and 1rem count as 16 px, whatever they turn out to be in a page. */
116
+ const PX: Readonly<Record<string, number>> = { px: 1, pt: 4 / 3, em: 16, rem: 16 };
117
+
118
+ interface Bounds {
119
+ /** Lengths, in px. Without it, no lengths. */
120
+ readonly px?: readonly [min: number, max: number];
121
+ /** Percentages. Without it, none. */
122
+ readonly percent?: readonly [min: number, max: number];
123
+ /** Bare numbers. Without it, only a bare zero, where lengths may be zero. */
124
+ readonly number?: readonly [min: number, max: number];
125
+ }
126
+
127
+ const within = (n: number, range: readonly [number, number]): boolean => n >= range[0] && n <= range[1];
128
+
129
+ /** A number with its unit, within bounds. Signs never parse: no negative length exists. */
130
+ const size =
131
+ (bounds: Bounds): Kind =>
132
+ (value) => {
133
+ const match = DIMENSION.exec(value);
134
+ if (match === null) return null;
135
+ const n = Number(match[1]);
136
+ const unit = match[2];
137
+ if (unit === undefined) {
138
+ if (bounds.number !== undefined) return within(n, bounds.number) ? value : null;
139
+ return n === 0 && bounds.px !== undefined && bounds.px[0] === 0 ? '0' : null;
140
+ }
141
+ if (unit === '%') return bounds.percent !== undefined && within(n, bounds.percent) ? value : null;
142
+ return bounds.px !== undefined && within(n * (PX[unit] as number), bounds.px) ? value : null;
143
+ };
144
+
145
+ const PALETTE_COLOR = /^var\(--astl-palette-[1-8](?:-soft)?\)$/;
146
+ const HEX_COLOR = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/;
147
+ const FUNCTION_COLOR = /^rgba?\(([^()]*)\)$/;
148
+
149
+ /** A hex colour or `rgb()`, or null: what has a value of its own, as opposed to a palette token or a keyword. */
150
+ export function parseStyleColor(value: string): StyleColor | null {
151
+ const text = value.trim().toLowerCase();
152
+ if (HEX_COLOR.test(text)) {
153
+ const digits = text.slice(1);
154
+ const short = digits.length < 6;
155
+ const pair = (i: number) =>
156
+ Number.parseInt(short ? `${digits.charAt(i)}${digits.charAt(i)}` : digits.slice(i * 2, i * 2 + 2), 16);
157
+ return [pair(0), pair(1), pair(2), digits.length % 4 === 0 ? pair(3) / 255 : 1];
158
+ }
159
+ const inner = FUNCTION_COLOR.exec(text)?.[1];
160
+ if (inner === undefined) return null;
161
+ const parts = inner.split(/[\s,/]+/).filter((part) => part !== '');
162
+ if (parts.length < 3 || parts.length > 4) return null;
163
+ const [red, green, blue] = parts.slice(0, 3).map((part) => (NUMBER.test(part) ? Number(part) : Number.NaN));
164
+ const written = parts[3] ?? '1';
165
+ const percent = written.endsWith('%');
166
+ const number = percent ? written.slice(0, -1) : written;
167
+ const alpha = NUMBER.test(number) ? Number(number) / (percent ? 100 : 1) : Number.NaN;
168
+ if (!(red !== undefined && green !== undefined && blue !== undefined)) return null;
169
+ if (!(red <= 255 && green <= 255 && blue <= 255 && alpha <= 1)) return null;
170
+ return [Math.round(red), Math.round(green), Math.round(blue), Math.round(alpha * 1000) / 1000];
171
+ }
172
+
173
+ /** A colour's normal form: `rgb(r, g, b)` for a function, as the browser writes it; hex stays hex, lowercase. */
174
+ const color: Kind = (value) => {
175
+ if (value === 'transparent' || value === 'currentcolor' || PALETTE_COLOR.test(value)) return value;
176
+ if (HEX_COLOR.test(value)) return value;
177
+ const parsed = parseStyleColor(value);
178
+ if (parsed === null) return null;
179
+ const [red, green, blue, alpha] = parsed;
180
+ return alpha === 1 ? `rgb(${red}, ${green}, ${blue})` : `rgba(${red}, ${green}, ${blue}, ${alpha})`;
181
+ };
182
+
183
+ /** A text colour: also legible by itself, so never transparent or nearly so. */
184
+ const inkColor: Kind = (value) => {
185
+ if (value === 'transparent') return null;
186
+ const parsed = parseStyleColor(value);
187
+ return parsed !== null && parsed[3] < 0.4 ? null : color(value);
188
+ };
189
+
190
+ const NAMED_FONT = /^[\p{L}\p{N} _-]{1,64}$/u;
191
+ const PLAIN_FONT = /^[\p{L}_][\p{L}\p{N} _-]{0,63}$/u;
192
+
193
+ /** A list of at most 8 font names: letters, digits, spaces, `_` and `-`, so never a function or an escape. */
194
+ const fontFamily: Kind = (value) => {
195
+ const names = splitTop(value, ',');
196
+ if (names.length === 0 || names.length > 8) return null;
197
+ const kept = names.map((name) => {
198
+ const quote = name.charAt(0);
199
+ if (quote !== '"' && quote !== "'") return PLAIN_FONT.test(name) ? name : null;
200
+ const inner = name.slice(1, -1);
201
+ return name.length > 2 && name.endsWith(quote) && NAMED_FONT.test(inner) ? `"${inner}"` : null;
202
+ });
203
+ return kept.includes(null) ? null : kept.join(', ');
204
+ };
205
+
206
+ /** The size words a browser may write back; `larger` and `smaller` are left out: nested, they have no bound. */
207
+ const fontSize = either(
208
+ words('xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'),
209
+ size({ px: [10, 96], percent: [62.5, 600] }),
210
+ );
211
+
212
+ const margin = either(words('auto'), size({ px: [0, 128], percent: [0, 50] }));
213
+ const padding = size({ px: [0, 64], percent: [0, 25] });
214
+ const measure = size({ px: [8, 1200], percent: [1, 100] });
215
+ const lineWidth = either(words('thin', 'medium', 'thick'), size({ px: [0, 16] }));
216
+ const lineStyle = words(
217
+ 'none',
218
+ 'hidden',
219
+ 'solid',
220
+ 'dashed',
221
+ 'dotted',
222
+ 'double',
223
+ 'groove',
224
+ 'ridge',
225
+ 'inset',
226
+ 'outset',
227
+ );
228
+ const corner = size({ px: [0, 128], percent: [0, 50] });
229
+ const gap = either(words('normal'), size({ px: [0, 64], percent: [0, 10] }));
230
+ const line = words('none', 'underline', 'overline', 'line-through');
231
+ const decorationStyle = words('solid', 'double', 'dotted', 'dashed', 'wavy');
232
+ const listType = words(
233
+ 'none',
234
+ 'disc',
235
+ 'circle',
236
+ 'square',
237
+ 'decimal',
238
+ 'decimal-leading-zero',
239
+ 'lower-alpha',
240
+ 'upper-alpha',
241
+ 'lower-latin',
242
+ 'upper-latin',
243
+ 'lower-roman',
244
+ 'upper-roman',
245
+ 'lower-greek',
246
+ );
247
+ const listPosition = words('inside', 'outside');
248
+
249
+ /** Up to three shadows, down and to the end only: offsets to 32 px, blur to 64 px, spread to 16 px. */
250
+ const boxShadow: Kind = (value) => {
251
+ if (value === 'none') return value;
252
+ const shadows = splitTop(value, ',');
253
+ if (shadows.length === 0 || shadows.length > 3) return null;
254
+ const limits = [size({ px: [0, 32] }), size({ px: [0, 32] }), size({ px: [0, 64] }), size({ px: [0, 16] })];
255
+ const kept = shadows.map((shadow) => {
256
+ let lengths = 0;
257
+ const parts = splitTop(shadow, ' ').map((part) => {
258
+ if (part === 'inset') return part;
259
+ const length = limits[lengths]?.(part) ?? null;
260
+ if (length !== null) lengths++;
261
+ return length ?? color(part);
262
+ });
263
+ return lengths < 2 || parts.includes(null) ? null : parts.join(' ');
264
+ });
265
+ return kept.includes(null) ? null : kept.join(', ');
266
+ };
267
+
268
+ const SIDES = [
269
+ 'top',
270
+ 'right',
271
+ 'bottom',
272
+ 'left',
273
+ 'inline',
274
+ 'block',
275
+ 'inline-start',
276
+ 'inline-end',
277
+ 'block-start',
278
+ 'block-end',
279
+ ];
280
+ const CORNERS = [
281
+ 'top-left',
282
+ 'top-right',
283
+ 'bottom-left',
284
+ 'bottom-right',
285
+ 'start-start',
286
+ 'start-end',
287
+ 'end-start',
288
+ 'end-end',
289
+ ];
290
+
291
+ const border = anyOrder(lineWidth, lineStyle, color);
292
+ /** How many values a side takes: `inline` and `block` have two ends, and browsers write different ends together. */
293
+ const ends = (side: string, kind: Kind): Kind => upTo(side === 'inline' || side === 'block' ? 2 : 1, kind);
294
+
295
+ /** The properties an author may set, each with what it may hold. Anything else is refused. */
296
+ const ALLOWED: ReadonlyMap<string, Kind> = new Map<string, Kind>([
297
+ // Text.
298
+ ['color', inkColor],
299
+ ['background-color', color],
300
+ ['font-family', fontFamily],
301
+ ['font-size', fontSize],
302
+ ['font-weight', either(words('normal', 'bold', 'bolder', 'lighter'), size({ number: [100, 900] }))],
303
+ ['font-style', words('normal', 'italic', 'oblique')],
304
+ ['text-decoration', anyOrder(line, line, line, decorationStyle, color)],
305
+ ['text-decoration-line', upTo(3, line)],
306
+ ['text-decoration-style', decorationStyle],
307
+ ['text-decoration-color', color],
308
+ ['text-align', words('left', 'right', 'center', 'justify', 'start', 'end')],
309
+ ['text-indent', size({ px: [0, 64], percent: [0, 25] })],
310
+ ['text-transform', words('none', 'uppercase', 'lowercase', 'capitalize')],
311
+ ['line-height', either(words('normal'), size({ number: [0.8, 4], px: [8, 160], percent: [80, 400] }))],
312
+ ['letter-spacing', either(words('normal'), size({ px: [0, 16] }))],
313
+ // Box.
314
+ ['margin', upTo(4, margin)],
315
+ ...SIDES.map((side): [string, Kind] => [`margin-${side}`, ends(side, margin)]),
316
+ ['padding', upTo(4, padding)],
317
+ ...SIDES.map((side): [string, Kind] => [`padding-${side}`, ends(side, padding)]),
318
+ ['border', border],
319
+ ['border-width', upTo(4, lineWidth)],
320
+ ['border-style', upTo(4, lineStyle)],
321
+ ['border-color', upTo(4, color)],
322
+ ...SIDES.flatMap((side): [string, Kind][] => [
323
+ [`border-${side}`, border],
324
+ [`border-${side}-width`, ends(side, lineWidth)],
325
+ [`border-${side}-style`, ends(side, lineStyle)],
326
+ [`border-${side}-color`, ends(side, color)],
327
+ ]),
328
+ // Nothing an author would write: Chromium expands `border` with it, and a style must survive that.
329
+ ['border-image', words('none', 'initial')],
330
+ ['border-radius', upTo(4, corner)],
331
+ ...CORNERS.map((at): [string, Kind] => [`border-${at}-radius`, upTo(2, corner)]),
332
+ ['box-shadow', boxShadow],
333
+ // Size and flow.
334
+ ['width', either(words('auto'), measure)],
335
+ ['max-width', either(words('none'), measure)],
336
+ ['inline-size', either(words('auto'), measure)],
337
+ ['max-inline-size', either(words('none'), measure)],
338
+ ['float', words('none', 'left', 'right', 'inline-start', 'inline-end')],
339
+ ['clear', words('none', 'left', 'right', 'both', 'inline-start', 'inline-end')],
340
+ ['display', words('block', 'inline', 'inline-block')],
341
+ ['vertical-align', words('baseline', 'top', 'middle', 'bottom', 'sub', 'super', 'text-top', 'text-bottom')],
342
+ // The third value is the image a browser may write back: `none` is the only one that exists here.
343
+ ['list-style', anyOrder(listType, listPosition, words('none'))],
344
+ ['list-style-type', listType],
345
+ ['list-style-position', listPosition],
346
+ // Columns.
347
+ ['gap', upTo(2, gap)],
348
+ ['column-gap', gap],
349
+ ['row-gap', gap],
350
+ ['align-items', words('normal', 'stretch', 'start', 'end', 'center', 'baseline', 'flex-start', 'flex-end')],
351
+ ['flex-grow', size({ number: [0, 12] })],
352
+ ]);
353
+
354
+ /** Every property a `style` may set, as a host lists them (`background` is read as `background-color`). */
355
+ export const STYLE_PROPERTIES: readonly string[] = [...ALLOWED.keys()];
356
+
357
+ /** Declarations in order, the later of one property in the place of the earlier: what the cascade would keep. */
358
+ export function mergeStyles(...lists: readonly (readonly StyleDeclaration[])[]): StyleDeclaration[] {
359
+ const merged = new Map<string, string>();
360
+ for (const list of lists) {
361
+ for (const [name, value] of list) {
362
+ // Deleted first, so it goes after a shorthand or longhand of the same box written earlier.
363
+ merged.delete(name);
364
+ merged.set(name, value);
365
+ }
366
+ }
367
+ return [...merged];
368
+ }
369
+
370
+ /** Declarations as a `style` value. */
371
+ export function styleText(declarations: readonly StyleDeclaration[]): string {
372
+ return declarations.map(([name, value]) => `${name}: ${value}`).join('; ');
373
+ }
374
+
375
+ const refusedName = (text: string): string => text.trim().slice(0, 40);
376
+
377
+ /**
378
+ * A `style` value through the allow-list: the declarations it may keep, and the names of those it may not. Refused:
379
+ * every property outside the table, and any declaration whose value is not exactly what the table allows (comments,
380
+ * escapes, `!important`, `url()`, custom properties, `var()` other than `--astl-palette-<n>` and its `-soft`, a size
381
+ * out of bounds). Idempotent, also on what browsers write back (`rgb(47, 86, 217)`, quoted font names, `0px`).
382
+ */
383
+ export function cleanStyle(value: string): CleanedStyle {
384
+ if (value.length > MAX_STYLE_LENGTH) return { style: '', declarations: [], removed: ['style'] };
385
+ const kept: StyleDeclaration[] = [];
386
+ const removed: string[] = [];
387
+ for (const part of splitTop(value, ';')) {
388
+ const colon = part.indexOf(':');
389
+ if (colon < 0) {
390
+ removed.push(refusedName(part));
391
+ continue;
392
+ }
393
+ const written = part.slice(0, colon).trim().toLowerCase();
394
+ const text = part.slice(colon + 1).trim();
395
+ // The browser's form of a background of one colour, and the one way to write it here.
396
+ const name = written === 'background' ? 'background-color' : written;
397
+ const kind = ALLOWED.get(name);
398
+ const clean = kind?.(name === 'font-family' ? text : text.toLowerCase()) ?? null;
399
+ if (clean === null) removed.push(refusedName(written));
400
+ else kept.push([name, clean]);
401
+ }
402
+ const declarations = mergeStyles(kept);
403
+ return { style: styleText(declarations), declarations, removed };
404
+ }
405
+
406
+ const channel = (value: number): number => {
407
+ const c = value / 255;
408
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
409
+ };
410
+
411
+ /** The WCAG relative luminance of a colour, its alpha left out. */
412
+ export function styleLuminance(value: StyleColor): number {
413
+ return 0.2126 * channel(value[0]) + 0.7152 * channel(value[1]) + 0.0722 * channel(value[2]);
414
+ }
415
+
416
+ /** `top` over `below`: what the eye sees of a colour with alpha. */
417
+ export function overStyleColor(top: StyleColor, below: StyleColor): StyleColor {
418
+ const a = top[3];
419
+ const mix = (i: 0 | 1 | 2) => top[i] * a + below[i] * (1 - a);
420
+ return [mix(0), mix(1), mix(2), 1];
421
+ }
422
+
423
+ /** The WCAG contrast ratio of an opaque text colour and background, from 1 to 21. */
424
+ export function styleContrast(ink: StyleColor, ground: StyleColor): number {
425
+ const [hi, lo] = [styleLuminance(ink), styleLuminance(ground)].sort((a, b) => b - a) as [number, number];
426
+ return (hi + 0.05) / (lo + 0.05);
427
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * ComponentDefinition: the grading side of one component type, registered with the engine.
3
+ * The engine owns parsing, sanitising, ids, pages, groups and hashing; a definition only answers
4
+ * "is this element valid", "which slots and keys does it produce" and "what does its public view look like".
5
+ */
6
+ import type { ElementNode } from './ast.js';
7
+ import type { Direction } from './format.js';
8
+ import type { MessageCatalog } from './i18n/types.js';
9
+ import type { IssueParams, Severity } from './issues.js';
10
+ import type { JsonObject } from './json.js';
11
+ import type { ComponentManifest } from './manifest.js';
12
+ import type { NormalisationProfile } from './slots.js';
13
+
14
+ export interface ValidateContext {
15
+ /** Content language at this element (nearest `lang`, else the document's). */
16
+ readonly lang: string;
17
+ /** Engine-wide text comparison defaults (for duplicate checks); definitions apply their own attributes on top. */
18
+ readonly profile: NormalisationProfile;
19
+ /**
20
+ * Reports an issue on the current element, or on one of its children (for a precise path).
21
+ * `code` must be listed in the manifest's `issues`. Default severity: `error`.
22
+ */
23
+ report(code: string, params?: IssueParams, options?: { severity?: Severity; child?: ElementNode }): void;
24
+ /**
25
+ * Another component on the same page, by source id, sanitised as its own definition sees it (a drop names its word
26
+ * bank); undefined when the page has none. Pages are played one at a time, so elements that work together share a
27
+ * page. Definitions run once the whole document is read, so the element may come later in the source.
28
+ */
29
+ find(id: string): ElementNode | undefined;
30
+ }
31
+
32
+ export interface CompileContext {
33
+ readonly lang: string;
34
+ readonly dir: Direction;
35
+ /** Engine-wide text comparison defaults; definitions apply their own attributes on top. */
36
+ readonly profile: NormalisationProfile;
37
+ /**
38
+ * Opaque id for the current element (no argument) or for a source id local to it, e.g. an option id.
39
+ * Deterministic for (secret, salt, element id, local id), so recompiling gives the same view.
40
+ */
41
+ opaque(localId?: string): string;
42
+ /**
43
+ * The opaque id of another component (by source id) or of a source id local to it, as that component's view writes
44
+ * it: what a drop's view and key need of its word bank. Throws for an id `validate` did not check (no such component,
45
+ * or no such local id).
46
+ */
47
+ opaqueOf(id: string, localId?: string): string;
48
+ /**
49
+ * Keyed permutation, a pure function of (element seed, `salt`, item count): calling it twice gives the same order,
50
+ * so `slots` and `toView` agree. With `avoidOriginal`, 2+ items never come back in source order (use it when the
51
+ * source order is the answer, e.g. ordering tasks). Use different salts for independent permutations.
52
+ */
53
+ permute<T>(items: readonly T[], options?: { avoidOriginal?: boolean; salt?: string }): T[];
54
+ }
55
+
56
+ /** One graded unit produced by an element. `key` must satisfy the registered SlotKind's `isKey`. */
57
+ export interface SlotSpec {
58
+ /** Opaque slot id, from `context.opaque(...)`. */
59
+ readonly id: string;
60
+ readonly kind: string;
61
+ readonly key: JsonObject;
62
+ }
63
+
64
+ /** A scoring group of an element graded in parts (see `ComponentDefinition.groups`). */
65
+ export interface GroupSpec {
66
+ /** Opaque group id, from `context.opaque(localId)`: never the element's own id or one of its slot ids. */
67
+ readonly id: string;
68
+ /** Some of the element's slot ids, in reading order. A slot may sit in several groups (a crossword's crossing). */
69
+ readonly slots: readonly string[];
70
+ }
71
+
72
+ export interface ComponentDefinition {
73
+ readonly manifest: ComponentManifest;
74
+ /** Catalogs of the manifest's namespace; the engine uses them to describe this type's issues. */
75
+ readonly messages?: readonly MessageCatalog[];
76
+ /**
77
+ * Type-specific checks on a sanitised element. The engine has already checked everything the manifest says
78
+ * (attribute types, enums, required attributes, child tags and counts, `id`).
79
+ */
80
+ validate(element: ElementNode, context: ValidateContext): void;
81
+ /**
82
+ * Local ids of slots that no child stands for (a crossword's cells), read from the valid element. Each gets an
83
+ * opaque id as a child's id does: `context.opaque(localId)`, fixture ref `<id>/<localId>`. Start them with a digit,
84
+ * so they never meet a child's id (source ids start with a letter). Absent: the children's ids only.
85
+ */
86
+ localIds?(element: ElementNode): readonly string[];
87
+ /** Slots with their private keys, in reading order. Called only for valid elements. */
88
+ slots(element: ElementNode, context: CompileContext): readonly SlotSpec[];
89
+ /**
90
+ * The scoring groups of an element graded in parts (a crossword's words): each scores by the rule of the
91
+ * element's scoring mode and gets its points, and together they hold every slot. Null or absent: one group, with
92
+ * the element's id, of all its slots. Called for valid graded elements only, after `slots`.
93
+ */
94
+ groups?(element: ElementNode, context: CompileContext): readonly GroupSpec[] | null;
95
+ /**
96
+ * The public view element. Must not contain private attributes or private children; the engine enforces the
97
+ * manifest allow-list afterwards and fails the compile if a private value would leak.
98
+ */
99
+ toView(element: ElementNode, context: CompileContext): ElementNode;
100
+ /** Extra numbers for metadata (e.g. `{ words: 12 }`), stored as `<tag>.<name>`. */
101
+ metadata?(element: ElementNode): Readonly<Record<string, number>>;
102
+ /** `migrations[n]` upgrades a source element written for version n to n + 1. */
103
+ readonly migrations?: Readonly<Record<number, (element: ElementNode) => ElementNode>>;
104
+ }