@parhelia/head 0.0.0-stage → 1.0.12903

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/src/refresh.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * `@parhelia/head/refresh` — **the in-place canvas refresh**: the `window.requestRefresh(newUri?)` contract Parhelia's editor
3
+ * calls after a save, so the page renders again in place instead of the frame reloading. The head says how to read the page
4
+ * again (`refetch`: the Pages Router's `router.replace` with a fresh query, the App Router's `router.refresh()`); this module
5
+ * decides when to stop.
6
+ *
7
+ * A save can land a moment after the editor asks, and a CMS's preview read can answer intermediate states, so the loop
8
+ * compares `signature()` (a stable string of what the page rendered): it reads again once a second until the signature changed
9
+ * from its state before the request and read the same twice (settled), or `deadlineMs` passed (an edit that changes nothing on
10
+ * this page). A new request restarts the loop. Every read of one request gets the editor's `newUri`.
11
+ *
12
+ * The module imports nothing (no React), so a head that links this package from a checkout and runs another React can call it
13
+ * from its own effect; `useParheliaRefresh` (the root entry) is the React hook around it.
14
+ */
15
+
16
+ /** How long a request keeps reading again by default. */
17
+ const DEFAULT_DEADLINE_MS = 8000;
18
+
19
+ /** The pause between two reads. */
20
+ const INTERVAL_MS = 1000;
21
+
22
+ /** @typedef {{ baseline?: string, lastSeen?: string, deadline: number, timer?: ReturnType<typeof setTimeout> }} PendingRefresh */
23
+
24
+ /**
25
+ * Installs `window.requestRefresh`; the answer removes it again and stops a running loop (an effect's cleanup).
26
+ * @param {{ refetch: (newUri?: string) => unknown, signature: () => string | undefined, deadlineMs?: number }} options
27
+ * @returns {() => void}
28
+ */
29
+ export function installParheliaRefresh({ refetch, signature, deadlineMs = DEFAULT_DEADLINE_MS }) {
30
+ /** @type {PendingRefresh | null} */
31
+ let pending = null;
32
+
33
+ /** @param {string | undefined} newUri */
34
+ const tick = newUri => {
35
+ const state = pending;
36
+ if (!state) return;
37
+ const current = signature();
38
+ if ((current !== state.baseline && current === state.lastSeen) || Date.now() > state.deadline) {
39
+ pending = null;
40
+ return;
41
+ }
42
+ state.lastSeen = current;
43
+ void refetch(newUri);
44
+ state.timer = setTimeout(() => tick(newUri), INTERVAL_MS);
45
+ };
46
+
47
+ const host = /** @type {{ requestRefresh?: (newUri?: string) => boolean }} */ (/** @type {unknown} */ (window));
48
+ host.requestRefresh = newUri => {
49
+ if (pending?.timer) clearTimeout(pending.timer);
50
+ /** @type {PendingRefresh} */
51
+ const state = { baseline: signature(), deadline: Date.now() + deadlineMs };
52
+ pending = state;
53
+ void refetch(newUri);
54
+ state.timer = setTimeout(() => tick(newUri), INTERVAL_MS);
55
+ return true;
56
+ };
57
+
58
+ return () => {
59
+ if (pending?.timer) clearTimeout(pending.timer);
60
+ pending = null;
61
+ delete host.requestRefresh;
62
+ };
63
+ }
@@ -0,0 +1,263 @@
1
+ /**
2
+ * The reader of `@parhelia/head/rich-text`: markup read with the HTML tokenizer's rules — the input stream's preprocessing, tags,
3
+ * attributes, comments, raw-text elements and character references in attribute values — as a browser reads it. The C# reader
4
+ * (`Parhelia.Markup`: `HtmlTokenizer`, `HtmlCharacterReferences`) follows the same rules; both run the one vector file beside this
5
+ * module (`rich-text.vectors.json`), so the two cannot drift apart unnoticed. Internal to the package (not in its exports).
6
+ */
7
+
8
+ /** Elements whose content the tokenizer reads as text up to their end tag (`plaintext`: to the end). */
9
+ export const RAW_TEXT_TAGS = new Set(["script", "style", "xmp", "iframe", "noembed", "noframes", "noscript", "textarea", "title"]);
10
+
11
+ /**
12
+ * The input stream's preprocessing: line breaks normalized and every NUL removed (a NUL is never content, so no reading may depend
13
+ * on where one stands).
14
+ * @param {string} html
15
+ */
16
+ export const preprocess = html => html.replace(/\r\n?/g, "\n").replace(/\0/g, "");
17
+
18
+ // ---- Character references ----------------------------------------------------------------------------------------------
19
+
20
+ /**
21
+ * The named references whose characters include ASCII (all of them, so a URL's scheme is read as a browser reads it), and
22
+ * the no-break space. Every other named reference decodes to characters outside ASCII.
23
+ * @type {Record<string, string>}
24
+ */
25
+ const NAMED_REFERENCES = {
26
+ Tab: "\t", NewLine: "\n", excl: "!", quot: '"', QUOT: '"', num: "#", dollar: "$", percnt: "%", amp: "&", AMP: "&",
27
+ apos: "'", lpar: "(", rpar: ")", ast: "*", midast: "*", plus: "+", comma: ",", period: ".", sol: "/", colon: ":",
28
+ semi: ";", lt: "<", LT: "<", equals: "=", gt: ">", GT: ">", quest: "?", commat: "@", lsqb: "[", lbrack: "[",
29
+ bsol: "\\", rsqb: "]", rbrack: "]", Hat: "^", lowbar: "_", UnderBar: "_", grave: "`", DiacriticalGrave: "`",
30
+ lcub: "{", lbrace: "{", verbar: "|", vert: "|", VerticalLine: "|", rcub: "}", rbrace: "}", fjlig: "fj",
31
+ nvlt: "<⃒", nvgt: ">⃒", bne: "=⃥", nbsp: " ", NonBreakingSpace: " ",
32
+ };
33
+
34
+ /**
35
+ * HTML 4's Latin-1 references (U+00A0 to U+00FF, in code point order): a browser decodes each with or without its semicolon
36
+ * (legacy references), as do the ASCII ones `amp`, `lt`, `gt`, `quot` and the upper-case `AMP`, `LT`, `GT`, `QUOT`, `COPY`, `REG`.
37
+ */
38
+ const LATIN_1 = (
39
+ "nbsp iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute micro para " +
40
+ "middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute " +
41
+ "Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml " +
42
+ "Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth " +
43
+ "ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml"
44
+ ).split(" ");
45
+
46
+ /** @type {Record<string, string>} */
47
+ const LEGACY_REFERENCES = Object.fromEntries([
48
+ ...LATIN_1.map((name, index) => [name, String.fromCharCode(0xa0 + index)]),
49
+ ["COPY", "©"], ["REG", "®"],
50
+ ["amp", "&"], ["AMP", "&"], ["lt", "<"], ["LT", "<"], ["gt", ">"], ["GT", ">"], ["quot", '"'], ["QUOT", '"'],
51
+ ]);
52
+
53
+ /** Numeric references to C1 controls are read as windows-1252. */
54
+ const WINDOWS_1252 = {
55
+ 0x80: 0x20ac, 0x82: 0x201a, 0x83: 0x0192, 0x84: 0x201e, 0x85: 0x2026, 0x86: 0x2020, 0x87: 0x2021, 0x88: 0x02c6,
56
+ 0x89: 0x2030, 0x8a: 0x0160, 0x8b: 0x2039, 0x8c: 0x0152, 0x8e: 0x017d, 0x91: 0x2018, 0x92: 0x2019, 0x93: 0x201c,
57
+ 0x94: 0x201d, 0x95: 0x2022, 0x96: 0x2013, 0x97: 0x2014, 0x98: 0x02dc, 0x99: 0x2122, 0x9a: 0x0161, 0x9b: 0x203a,
58
+ 0x9c: 0x0153, 0x9e: 0x017e, 0x9f: 0x0178,
59
+ };
60
+
61
+ /** @param {string} digits @param {number} radix */
62
+ function numericReference(digits, radix) {
63
+ const significant = digits.replace(/^0+/, "");
64
+ const code = significant.length > 8 ? Infinity : significant === "" ? 0 : Number.parseInt(significant, radix);
65
+ if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return "�";
66
+ return String.fromCodePoint(/** @type {Record<number, number>} */ (WINDOWS_1252)[code] ?? code);
67
+ }
68
+
69
+ const REFERENCE = /&(?:#[xX]([0-9a-fA-F]+);?|#([0-9]+);?|([A-Za-z][A-Za-z0-9]*)(;?))/g;
70
+
71
+ /**
72
+ * An attribute value as a browser decodes it, in parts; an opaque part is a named reference left for the browser (one this
73
+ * module does not know: it decodes to characters outside ASCII and Latin-1).
74
+ * @param {string} raw
75
+ * @returns {{ text: string; opaque: boolean }[]}
76
+ */
77
+ export function decodeAttribute(raw) {
78
+ /** @type {{ text: string; opaque: boolean }[]} */
79
+ const parts = [];
80
+ let last = 0;
81
+ for (const match of raw.matchAll(REFERENCE)) {
82
+ const [whole, hex, decimal, name = "", semicolon] = match;
83
+ /** @type {string} */
84
+ let text;
85
+ let opaque = false;
86
+ if (hex !== undefined) text = numericReference(hex, 16);
87
+ else if (decimal !== undefined) text = numericReference(decimal, 10);
88
+ else if (semicolon && Object.hasOwn(NAMED_REFERENCES, name)) text = /** @type {string} */ (NAMED_REFERENCES[name]);
89
+ else if (semicolon && Object.hasOwn(LEGACY_REFERENCES, name)) text = /** @type {string} */ (LEGACY_REFERENCES[name]);
90
+ else if (semicolon) {
91
+ text = whole;
92
+ opaque = true;
93
+ } else if (Object.hasOwn(LEGACY_REFERENCES, name) && raw.charAt(match.index + whole.length) !== "=") {
94
+ // Without the semicolon only a legacy name decodes, and in an attribute not when '=' follows (a letter or digit cannot:
95
+ // the name runs over them).
96
+ text = /** @type {string} */ (LEGACY_REFERENCES[name]);
97
+ } else continue;
98
+ if (match.index > last) parts.push({ text: raw.slice(last, match.index), opaque: false });
99
+ parts.push({ text, opaque });
100
+ last = match.index + whole.length;
101
+ }
102
+ if (last < raw.length) parts.push({ text: raw.slice(last), opaque: false });
103
+ return parts;
104
+ }
105
+
106
+ // ---- Reading -----------------------------------------------------------------------------------------------------------
107
+
108
+ /**
109
+ * @typedef {{ type: "start"; name: string; attributes: [string, string][]; selfClosing: boolean }} StartToken
110
+ * @typedef {StartToken | { type: "end"; name: string } | { type: "text"; value: string }} Token
111
+ */
112
+
113
+ const WHITESPACE = /[\t\n\f ]/;
114
+ const ALPHA = /[A-Za-z]/;
115
+
116
+ /**
117
+ * The tokens of a fragment, by the HTML tokenizer's data, tag, attribute, comment and raw-text states. Comments, doctypes
118
+ * and bogus comments yield nothing; a tag cut off by the end of the input yields nothing (as in a browser); the content of
119
+ * a raw-text element yields nothing (only dropped elements have one).
120
+ * @param {string} input
121
+ * @returns {Generator<Token>}
122
+ */
123
+ export function* tokenize(input) {
124
+ const length = input.length;
125
+ let i = 0;
126
+ let text = "";
127
+ while (i < length) {
128
+ const lt = input.indexOf("<", i);
129
+ if (lt < 0) {
130
+ text += input.slice(i);
131
+ break;
132
+ }
133
+ text += input.slice(i, lt);
134
+ i = lt + 1;
135
+ const next = input.charAt(i);
136
+ if (next === "!") {
137
+ i = skipMarkupDeclaration(input, i + 1);
138
+ } else if (next === "?") {
139
+ i = skipBogusComment(input, i);
140
+ } else if (next === "/") {
141
+ const after = input[i + 1];
142
+ if (after === undefined) {
143
+ text += "</";
144
+ i = length;
145
+ } else if (after === ">") {
146
+ i += 2;
147
+ } else if (ALPHA.test(after)) {
148
+ const tag = readTag(input, i + 1);
149
+ if (!tag) break; // cut off by the end of the input
150
+ if (text) yield { type: "text", value: text };
151
+ text = "";
152
+ yield { type: "end", name: tag.name };
153
+ i = tag.end;
154
+ } else {
155
+ i = skipBogusComment(input, i + 1);
156
+ }
157
+ } else if (ALPHA.test(next)) {
158
+ const tag = readTag(input, i);
159
+ if (!tag) break;
160
+ if (text) yield { type: "text", value: text };
161
+ text = "";
162
+ yield { type: "start", name: tag.name, attributes: tag.attributes, selfClosing: tag.selfClosing };
163
+ i = tag.end;
164
+ if (tag.name === "plaintext") return;
165
+ if (RAW_TEXT_TAGS.has(tag.name)) i = rawTextEnd(input, i, tag.name);
166
+ } else {
167
+ text += "<";
168
+ }
169
+ }
170
+ if (text) yield { type: "text", value: text };
171
+ }
172
+
173
+ /** After `<!`: a comment (`<!-->` and `<!--->` end at once), a doctype or a bogus comment, up to its end. */
174
+ function skipMarkupDeclaration(/** @type {string} */ input, /** @type {number} */ i) {
175
+ if (input.startsWith("--", i)) {
176
+ let at = i + 2;
177
+ if (input[at] === ">") return at + 1;
178
+ if (input.startsWith("->", at)) return at + 2;
179
+ for (;;) {
180
+ const dash = input.indexOf("--", at);
181
+ if (dash < 0) return input.length;
182
+ if (input[dash + 2] === ">") return dash + 3;
183
+ if (input.startsWith("!>", dash + 2)) return dash + 4;
184
+ at = dash + 1;
185
+ }
186
+ }
187
+ return skipBogusComment(input, i);
188
+ }
189
+
190
+ /** A bogus comment or doctype: up to the next `>`. */
191
+ function skipBogusComment(/** @type {string} */ input, /** @type {number} */ i) {
192
+ const end = input.indexOf(">", i);
193
+ return end < 0 ? input.length : end + 1;
194
+ }
195
+
196
+ /** The position after a raw-text element's content: at its end tag (`</name` and white space, `/` or `>`), or the end. */
197
+ function rawTextEnd(/** @type {string} */ input, /** @type {number} */ i, /** @type {string} */ name) {
198
+ const close = new RegExp(`</${name}(?=[\\t\\n\\f />]|$)`, "gi");
199
+ close.lastIndex = i;
200
+ return close.exec(input)?.index ?? input.length;
201
+ }
202
+
203
+ /**
204
+ * A tag from its name's first character to after its `>`: the lowercase name, the attributes (lowercase names, raw values)
205
+ * and the self-closing flag; null when the input ends inside it.
206
+ * @param {string} input @param {number} start
207
+ * @returns {{ name: string; attributes: [string, string][]; selfClosing: boolean; end: number } | null}
208
+ */
209
+ function readTag(input, start) {
210
+ const length = input.length;
211
+ let i = start;
212
+ while (i < length && !isTagNameEnd(input.charAt(i))) i++;
213
+ const name = input.slice(start, i).toLowerCase();
214
+ /** @type {[string, string][]} */
215
+ const attributes = [];
216
+ let selfClosing = false;
217
+ for (;;) {
218
+ // Before an attribute name.
219
+ while (i < length && WHITESPACE.test(input.charAt(i))) i++;
220
+ if (i >= length) return null;
221
+ let char = input.charAt(i);
222
+ if (char === ">") return { name, attributes, selfClosing, end: i + 1 };
223
+ if (char === "/") {
224
+ i++;
225
+ if (i >= length) return null;
226
+ if (input.charAt(i) === ">") {
227
+ selfClosing = true;
228
+ return { name, attributes, selfClosing, end: i + 1 };
229
+ }
230
+ continue;
231
+ }
232
+ // An attribute name: a leading "=" is part of it.
233
+ const nameStart = i;
234
+ i++;
235
+ while (i < length && !isTagNameEnd(input.charAt(i)) && input.charAt(i) !== "=") i++;
236
+ const attributeName = input.slice(nameStart, i).toLowerCase();
237
+ // After the name.
238
+ while (i < length && WHITESPACE.test(input.charAt(i))) i++;
239
+ if (i >= length) return null;
240
+ if (input.charAt(i) !== "=") {
241
+ attributes.push([attributeName, ""]);
242
+ continue;
243
+ }
244
+ i++;
245
+ while (i < length && WHITESPACE.test(input.charAt(i))) i++;
246
+ if (i >= length) return null;
247
+ char = input.charAt(i);
248
+ if (char === '"' || char === "'") {
249
+ const close = input.indexOf(char, i + 1);
250
+ if (close < 0) return null;
251
+ attributes.push([attributeName, input.slice(i + 1, close)]);
252
+ i = close + 1;
253
+ } else if (char === ">") {
254
+ attributes.push([attributeName, ""]);
255
+ } else {
256
+ const valueStart = i;
257
+ while (i < length && !WHITESPACE.test(input.charAt(i)) && input.charAt(i) !== ">") i++;
258
+ attributes.push([attributeName, input.slice(valueStart, i)]);
259
+ }
260
+ }
261
+ }
262
+
263
+ const isTagNameEnd = (/** @type {string} */ char) => char === "/" || char === ">" || WHITESPACE.test(char);
@@ -0,0 +1,17 @@
1
+ /**
2
+ * What the rich-text rule does with an element of the HTML namespace: keep it, unwrap it (its content stays) or drop it
3
+ * with its content. Elements of another namespace (SVG, MathML) are dropped.
4
+ */
5
+ export declare function richTextElementAction(tag: string): "keep" | "unwrap" | "drop";
6
+
7
+ /**
8
+ * The value an attribute keeps on an allowlisted element, or null when the rule removes it. `value` is the attribute's
9
+ * value as a browser reads it (character references decoded). A style keeps its formatting declarations only.
10
+ */
11
+ export declare function sanitizeRichTextAttribute(tag: string, name: string, value: string): string | null;
12
+
13
+ /**
14
+ * Filters rich-text HTML down to the rule and writes it again (server or browser, no DOM needed); `""` for anything but a
15
+ * string.
16
+ */
17
+ export declare function sanitizeRichTextHtml(html: string): string;