@rohal12/spindle 0.59.22 → 0.59.25

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.
@@ -0,0 +1,331 @@
1
+ /**
2
+ * Pairing: which closer closes which opener among the flat tokens of markup
3
+ * (parse.ts tokenizeMarkup), and which branch (`{else}`, `{case}`) belongs to
4
+ * which macro. The runtime AST (ast.ts) is built from this, and editor tooling
5
+ * reads the same tree (`pairMarkup` in tooling.ts), so both agree on where a
6
+ * block starts and ends.
7
+ *
8
+ * It never throws: a problem is an entry of `errors`, and the tree is
9
+ * recovered around it. A closer closes the innermost open element, as the
10
+ * runtime reads it, or, when it matches one further out, closes that one and
11
+ * what was open inside it stays unclosed.
12
+ */
13
+ import { lineColumn } from './line-column';
14
+ import { isBlockMacro, isRawMacro } from './ast';
15
+ import type { HtmlToken, MacroToken, Span, Token } from './tokens';
16
+
17
+ /** What is wrong with the pairing, by kind. */
18
+ export type PairingErrorCode =
19
+ | 'unclosed-block'
20
+ | 'mismatched-closer'
21
+ | 'stray-closer'
22
+ | 'misplaced-branch';
23
+
24
+ /**
25
+ * A problem in the pairing of the tokens, at the token from `start` up to
26
+ * `end` (offsets in the source).
27
+ */
28
+ export interface PairingError extends Span {
29
+ code: PairingErrorCode;
30
+ /** What is wrong, without the position. */
31
+ message: string;
32
+ /**
33
+ * The offset a parser reading left to right notices it at: where the
34
+ * closer ends, or past the end of the markup for what is left open there.
35
+ */
36
+ noticedAt: number;
37
+ /** The names involved, by code (see MarkupError.data). */
38
+ data: Record<string, string>;
39
+ }
40
+
41
+ /** A branch (`{else}`, `{case}`, …) of a macro, with what follows it. */
42
+ export interface PairedBranch {
43
+ tag: MacroToken;
44
+ children: PairedNode[];
45
+ }
46
+
47
+ /** What a macro or element holds, up to its closer. */
48
+ export interface PairedBody {
49
+ children: PairedNode[];
50
+ branches: PairedBranch[];
51
+ /** The closing tag; absent if it is never closed. */
52
+ close?: MacroToken | HtmlToken;
53
+ }
54
+
55
+ /**
56
+ * A node of the tree: a token that stands alone (text, a link, a variable, an
57
+ * expression, a macro without a body, a self-closing element), or the opening
58
+ * tag of a macro or element with its `body`.
59
+ */
60
+ export interface PairedNode {
61
+ /** The token, or the opening tag of the element. */
62
+ token: Token;
63
+ body?: PairedBody;
64
+ /** From the start of the token to the end of the closer (or of the body). */
65
+ start: number;
66
+ end: number;
67
+ }
68
+
69
+ export interface PairMarkupOptions {
70
+ /** Whether a macro takes a body (default: the registered block macros). */
71
+ isBlock?(name: string): boolean;
72
+ /**
73
+ * Whether a macro's body is JavaScript, kept verbatim as one text token
74
+ * (default: `{do}`). One that is never closed is a problem at its opening
75
+ * tag, where the body would start, and the markup after it is not its body.
76
+ */
77
+ isRaw?(name: string): boolean;
78
+ /**
79
+ * The markup the tokens are of: lets a message say at which line and column
80
+ * an element was opened (else it says at which offset).
81
+ */
82
+ source?: string;
83
+ }
84
+
85
+ export interface PairedMarkup {
86
+ nodes: PairedNode[];
87
+ errors: PairingError[];
88
+ }
89
+
90
+ /** The last of `items`. */
91
+ const last = <T>(items: readonly T[]): T | undefined => items[items.length - 1];
92
+
93
+ /** The macro each branch macro belongs to. */
94
+ export const BRANCH_PARENT: Readonly<Record<string, string>> = {
95
+ elseif: 'if',
96
+ else: 'if',
97
+ case: 'switch',
98
+ default: 'switch',
99
+ next: 'timed',
100
+ };
101
+
102
+ const isBranchTag = (token: Token): boolean =>
103
+ token.type === 'macro' &&
104
+ !token.isClose &&
105
+ Object.prototype.hasOwnProperty.call(BRANCH_PARENT, token.name.toLowerCase());
106
+
107
+ const lowerName = (token: MacroToken | HtmlToken) =>
108
+ nameOf(token).toLowerCase();
109
+
110
+ /** The macro name or HTML tag of `tag`, as written. */
111
+ const nameOf = (tag: MacroToken | HtmlToken): string =>
112
+ tag.type === 'macro' ? tag.name : tag.tag;
113
+
114
+ /** How a tag reads in an error message. */
115
+ export function tagLabel(tag: MacroToken | HtmlToken): string {
116
+ return tag.type === 'html'
117
+ ? `${tag.isClose ? '</' : '<'}${tag.tag}>`
118
+ : `{${tag.isClose ? '/' : ''}${tag.name}}`;
119
+ }
120
+
121
+ /** The tag that closes the element opened by `tag`. */
122
+ const closerOf = (tag: MacroToken | HtmlToken): string =>
123
+ tag.type === 'html' ? `</${tag.tag}>` : `{/${tag.name}}`;
124
+
125
+ /** An element being read: its opening tag, and what it holds so far. */
126
+ interface Frame {
127
+ node: PairedNode;
128
+ body: PairedBody;
129
+ /** Where the next child goes: the body, or its last branch. */
130
+ into: PairedNode[];
131
+ }
132
+
133
+ /** How an element ends: with its closer, or without. */
134
+ type Ending = 'closed' | 'unclosed' | 'mismatch' | 'cut';
135
+
136
+ /** Whether `close` is the closing tag of the element opened by `open`. */
137
+ const closes = (open: Token, close: MacroToken | HtmlToken): boolean =>
138
+ open.type === close.type &&
139
+ lowerName(open as MacroToken | HtmlToken) === lowerName(close);
140
+
141
+ /**
142
+ * Pair `tokens`, the tokens of `source`, into a tree: elements with their
143
+ * bodies and branches, and the problems found (unclosed, mismatched and
144
+ * stray closers, branches outside their macro) in the order a parser reading
145
+ * from left to right notices them.
146
+ */
147
+ export function pairMarkup(
148
+ tokens: readonly Token[],
149
+ options: PairMarkupOptions = {},
150
+ ): PairedMarkup {
151
+ const isBlock = options.isBlock ?? isBlockMacro;
152
+ const isRaw = options.isRaw ?? isRawMacro;
153
+ const errors: PairingError[] = [];
154
+ const noticedAtEnd = (tokens[tokens.length - 1]?.end ?? 0) + 1;
155
+ const where = (offset: number) => {
156
+ if (options.source === undefined) return `offset ${offset}`;
157
+ const { line, column } = lineColumn(options.source, offset);
158
+ return `line ${line}, column ${column}`;
159
+ };
160
+ const report = (
161
+ code: PairingErrorCode,
162
+ token: Token,
163
+ message: string,
164
+ noticedAt: number,
165
+ data: Record<string, string>,
166
+ ) => {
167
+ errors.push({
168
+ code,
169
+ message,
170
+ start: token.start,
171
+ end: token.end,
172
+ noticedAt,
173
+ data,
174
+ });
175
+ };
176
+
177
+ /** A branch outside its macro, or inside another element `inside`. */
178
+ const misplaced = (
179
+ tag: MacroToken,
180
+ inside: MacroToken | HtmlToken | undefined,
181
+ noticedAt: number,
182
+ ) => {
183
+ const parent = BRANCH_PARENT[tag.name.toLowerCase()]!;
184
+ const where = inside ? `, not inside ${tagLabel(inside)}` : '';
185
+ report(
186
+ 'misplaced-branch',
187
+ tag,
188
+ `${tagLabel(tag)} must be directly inside {${parent}}${where}`,
189
+ noticedAt,
190
+ { name: tag.name, parent, ...(inside && { inside: nameOf(inside) }) },
191
+ );
192
+ };
193
+
194
+ const root: PairedNode[] = [];
195
+ const stack: Frame[] = [];
196
+ const add = (node: PairedNode) => (last(stack)?.into ?? root).push(node);
197
+
198
+ /**
199
+ * End the element on top of the stack, with `close` if it has one: its
200
+ * misplaced branches are reported first, then how it ends.
201
+ */
202
+ const end = (
203
+ ending: Ending,
204
+ close?: MacroToken | HtmlToken,
205
+ owns = ending === 'closed',
206
+ ) => {
207
+ const { node, body } = stack.pop()!;
208
+ const open = node.token as MacroToken | HtmlToken;
209
+ const noticedAt = close ? close.end : noticedAtEnd;
210
+ for (const { tag } of body.branches) {
211
+ const parent = BRANCH_PARENT[tag.name.toLowerCase()]!;
212
+ if (open.type !== 'macro' || lowerName(open) !== parent) {
213
+ misplaced(tag, open, noticedAt);
214
+ }
215
+ }
216
+ if (ending === 'unclosed') {
217
+ report(
218
+ 'unclosed-block',
219
+ open,
220
+ `Unclosed ${tagLabel(open)}: no ${closerOf(open)} closes it`,
221
+ noticedAt,
222
+ { name: nameOf(open) },
223
+ );
224
+ } else if (ending === 'mismatch') {
225
+ report(
226
+ 'mismatched-closer',
227
+ close!,
228
+ `${tagLabel(close!)} found where ${closerOf(open)} should close the ${tagLabel(open)} opened at ${where(open.start)}`,
229
+ noticedAt,
230
+ { name: nameOf(open), closer: nameOf(close!) },
231
+ );
232
+ }
233
+ if (owns) body.close = close;
234
+ node.end = body.close?.end ?? lastEnd(body) ?? open.end;
235
+ add(node);
236
+ };
237
+
238
+ for (let i = 0; i < tokens.length; i++) {
239
+ const token = tokens[i]!;
240
+ if ((token.type === 'macro' || token.type === 'html') && token.isClose) {
241
+ const top = last(stack);
242
+ if (!top) {
243
+ report(
244
+ 'stray-closer',
245
+ token,
246
+ `${tagLabel(token)} closes nothing: no ${token.type === 'html' ? `<${token.tag}>` : `{${token.name}}`} is open here`,
247
+ token.start,
248
+ { name: nameOf(token) },
249
+ );
250
+ } else if (closes(top.node.token, token)) {
251
+ end('closed', token);
252
+ } else {
253
+ // The closer ends the innermost element, as the runtime reads it;
254
+ // when it names one further out, it ends that one, and the elements
255
+ // inside it are left unclosed
256
+ let outer = stack.length - 1;
257
+ while (outer >= 0 && !closes(stack[outer]!.node.token, token)) outer--;
258
+ end('mismatch', token, outer === -1);
259
+ if (outer !== -1) {
260
+ while (stack.length > outer + 1) end('cut', token);
261
+ end('closed', token);
262
+ }
263
+ }
264
+ continue;
265
+ }
266
+ if (isBranchTag(token)) {
267
+ const tag = token as MacroToken;
268
+ const frame = last(stack);
269
+ if (!frame) {
270
+ misplaced(tag, undefined, tag.start);
271
+ continue;
272
+ }
273
+ const branch: PairedBranch = { tag, children: [] };
274
+ frame.body.branches.push(branch);
275
+ frame.into = branch.children;
276
+ continue;
277
+ }
278
+ const node: PairedNode = { token, start: token.start, end: token.end };
279
+ const opens =
280
+ token.type === 'html'
281
+ ? !token.isSelfClose
282
+ : token.type === 'macro' && isBlock(token.name.toLowerCase());
283
+ if (
284
+ opens &&
285
+ token.type === 'macro' &&
286
+ isRaw(token.name.toLowerCase()) &&
287
+ !closesRawBody(token, tokens[i + 1], tokens[i + 2])
288
+ ) {
289
+ // Its body is looked for as soon as the tag is read: the markup after
290
+ // it is not its body
291
+ report(
292
+ 'unclosed-block',
293
+ token,
294
+ `Unclosed ${tagLabel(token)}: no ${closerOf(token)} closes it`,
295
+ token.end,
296
+ { name: nameOf(token) },
297
+ );
298
+ add(node);
299
+ continue;
300
+ }
301
+ if (!opens) {
302
+ add(node);
303
+ continue;
304
+ }
305
+ const body: PairedBody = { children: [], branches: [] };
306
+ node.body = body;
307
+ stack.push({ node, body, into: body.children });
308
+ }
309
+ while (stack.length > 0) end('unclosed');
310
+ return { nodes: root, errors };
311
+ }
312
+
313
+ /**
314
+ * Whether the tokens after the opening tag `open` of a raw macro are its
315
+ * body (one text token, if it is not empty) and its closer.
316
+ */
317
+ function closesRawBody(
318
+ open: MacroToken,
319
+ next: Token | undefined,
320
+ after: Token | undefined,
321
+ ): boolean {
322
+ const closer = (t: Token | undefined) =>
323
+ t?.type === 'macro' && t.isClose && closes(open, t);
324
+ return closer(next) || (next?.type === 'text' && closer(after));
325
+ }
326
+
327
+ /** The end of the last thing in `body`. */
328
+ function lastEnd(body: PairedBody): number | undefined {
329
+ const branch = last(body.branches);
330
+ return last(branch?.children ?? body.children)?.end ?? branch?.tag.end;
331
+ }
@@ -4,13 +4,19 @@
4
4
  * as a MarkupError carrying its line and column.
5
5
  */
6
6
  import { parse as pegParse } from './spindle.peggy';
7
- import { isBlockMacro, type ASTNode } from './ast';
7
+ import { buildAst, isBlockMacro, isRawMacro, type ASTNode } from './ast';
8
+ import {
9
+ pairMarkup,
10
+ type PairedNode,
11
+ type PairingError,
12
+ type PairingErrorCode,
13
+ } from './pair';
8
14
  import type { Selectors, Token } from './tokens';
9
15
  import { isCodeAttribute } from './code-attributes';
10
16
  import { defaultCodeEnd, type CodeEnd } from './code-end';
17
+ import { lineColumn } from './line-column';
11
18
 
12
- /** Macros whose body is JavaScript source, kept verbatim. */
13
- const RAW_BODY_MACROS = new Set(['do']);
19
+ export { lineColumn };
14
20
 
15
21
  /** What the grammar leaves to code. */
16
22
  export interface MarkupHooks extends CodeEnd {
@@ -25,10 +31,24 @@ export interface MarkupHooks extends CodeEnd {
25
31
  const defaultHooks: MarkupHooks = {
26
32
  ...defaultCodeEnd,
27
33
  isBlock: isBlockMacro,
28
- isRaw: (name) => RAW_BODY_MACROS.has(name),
34
+ isRaw: isRawMacro,
29
35
  isCodeAttribute,
30
36
  };
31
37
 
38
+ /** The kinds of malformed markup (see MarkupError.code). */
39
+ export type MarkupErrorCode =
40
+ | PairingErrorCode
41
+ | 'syntax'
42
+ | 'unclosed-link'
43
+ | 'unclosed-expression'
44
+ | 'unclosed-macro'
45
+ | 'invalid-closer'
46
+ | 'closer-with-selectors'
47
+ | 'closer-with-arguments'
48
+ | 'unclosed-tag'
49
+ | 'unexpected-character'
50
+ | 'unclosed-attribute';
51
+
32
52
  /** Malformed markup, with where it starts (1-based line and column). */
33
53
  export class MarkupError extends Error {
34
54
  constructor(
@@ -38,6 +58,15 @@ export class MarkupError extends Error {
38
58
  readonly offset: number,
39
59
  readonly line: number,
40
60
  readonly column: number,
61
+ /** The kind of error, which stays the same where the wording changes. */
62
+ readonly code: MarkupErrorCode = 'syntax',
63
+ /** Where the offending text ends (0-based, exclusive). */
64
+ readonly end: number = offset,
65
+ /**
66
+ * The names involved, by `code`: `name` for an unclosed, mismatched or
67
+ * stray tag (and `closer`, `parent`, `inside` where there are several).
68
+ */
69
+ readonly data: Readonly<Record<string, string>> = {},
41
70
  ) {
42
71
  super(`${reason} (line ${line}, column ${column})`);
43
72
  this.name = 'MarkupError';
@@ -57,24 +86,9 @@ export interface ParseMarkupOptions {
57
86
  hooks?: Partial<MarkupHooks>;
58
87
  }
59
88
 
60
- /** 1-based line and column of `offset` in `text`. */
61
- export function lineColumn(
62
- text: string,
63
- offset: number,
64
- ): { line: number; column: number } {
65
- let line = 1;
66
- let lineStart = 0;
67
- for (let i = text.indexOf('\n'); i !== -1 && i < offset; ) {
68
- line++;
69
- lineStart = i + 1;
70
- i = text.indexOf('\n', lineStart);
71
- }
72
- return { line, column: offset - lineStart + 1 };
73
- }
74
-
75
89
  function run(
76
90
  source: string,
77
- startRule: 'Markup' | 'Tokens' | 'SelectorsPrefix',
91
+ startRule: 'Tokens' | 'SelectorsPrefix',
78
92
  options: ParseMarkupOptions,
79
93
  ): unknown {
80
94
  const hooks = options.hooks
@@ -83,26 +97,103 @@ function run(
83
97
  try {
84
98
  return pegParse(source, { startRule, text: options.text === true, hooks });
85
99
  } catch (err) {
86
- const location = (err as { location?: { start: { offset: number } } })
87
- .location;
100
+ const { location, code } = err as {
101
+ location?: { start: { offset: number }; end: { offset: number } };
102
+ code?: MarkupErrorCode;
103
+ };
88
104
  if (err instanceof Error && err.name === 'SyntaxError' && location) {
89
105
  const { offset } = location.start;
90
106
  const { line, column } = lineColumn(source, offset);
91
- throw new MarkupError(err.message, offset, line, column);
107
+ throw new MarkupError(
108
+ err.message,
109
+ offset,
110
+ line,
111
+ column,
112
+ code,
113
+ location.end.offset,
114
+ );
92
115
  }
93
116
  throw err;
94
117
  }
95
118
  }
96
119
 
120
+ /** What tolerant parsing makes of markup (see analyzeMarkup). */
121
+ export interface MarkupAnalysis {
122
+ tokens: Token[];
123
+ /** The tokens paired into elements (see pair.ts). */
124
+ nodes: PairedNode[];
125
+ /**
126
+ * Every problem, in the order a parser reading from left to right notices
127
+ * them: the first is the one parseMarkup throws.
128
+ */
129
+ errors: MarkupError[];
130
+ }
131
+
132
+ /**
133
+ * Read markup that may be malformed: its tokens, their pairing and every
134
+ * error (malformed tags, and closers and branches that pair with nothing),
135
+ * with offsets in `source`. Markup inside a malformed tag is not read as such,
136
+ * so it has no errors of its own.
137
+ */
138
+ export function analyzeMarkup(
139
+ source: string,
140
+ options: ParseMarkupOptions = {},
141
+ ): MarkupAnalysis {
142
+ const { tokens, errors, damage } = scan(source, options);
143
+ const hooks = { ...defaultHooks, ...options.hooks };
144
+ const paired = pairMarkup(tokens, {
145
+ isBlock: hooks.isBlock,
146
+ isRaw: hooks.isRaw,
147
+ source,
148
+ });
149
+ if (errors.length === 0 && paired.errors.length === 0) {
150
+ return { tokens, nodes: paired.nodes, errors };
151
+ }
152
+ // A malformed tag is noticed where it starts, an unpaired tag where its
153
+ // problem shows (see PairingError.noticedAt). Within a malformed tag the
154
+ // markup is no markup: what the recovery pairs there is dropped.
155
+ const inDamage = (start: number) =>
156
+ errors.some((e, i) => start >= damage[i]! && start <= e.offset);
157
+ const noticed: [number, MarkupError][] = errors.map((e, i) => [
158
+ damage[i]! + 0.5,
159
+ e,
160
+ ]);
161
+ for (const error of paired.errors) {
162
+ if (!inDamage(error.start)) {
163
+ noticed.push([error.noticedAt, pairingError(source, error)]);
164
+ }
165
+ }
166
+ // Array.prototype.sort is stable: equal ones stay in the order found
167
+ noticed.sort((a, b) => a[0] - b[0]);
168
+ return { tokens, nodes: paired.nodes, errors: noticed.map(([, e]) => e) };
169
+ }
170
+
97
171
  /**
98
172
  * Parse markup into its AST: macros with their bodies and branches, HTML
99
- * elements with their children. Throws a MarkupError for malformed markup.
173
+ * elements with their children. Throws a MarkupError for malformed markup:
174
+ * the first problem a parser reading from left to right meets.
100
175
  */
101
176
  export function parseMarkup(
102
177
  source: string,
103
178
  options: ParseMarkupOptions = {},
104
179
  ): ASTNode[] {
105
- return run(source, 'Markup', options) as ASTNode[];
180
+ const { nodes, errors } = analyzeMarkup(source, options);
181
+ if (errors.length > 0) throw errors[0];
182
+ return buildAst(nodes);
183
+ }
184
+
185
+ /** A pairing problem as the MarkupError it is for `source`. */
186
+ function pairingError(source: string, error: PairingError): MarkupError {
187
+ const { line, column } = lineColumn(source, error.start);
188
+ return new MarkupError(
189
+ error.message,
190
+ error.start,
191
+ line,
192
+ column,
193
+ error.code,
194
+ error.end,
195
+ error.data,
196
+ );
106
197
  }
107
198
 
108
199
  /**
@@ -151,8 +242,22 @@ export function tokenizeMarkupTolerant(
151
242
  source: string,
152
243
  options: ParseMarkupOptions = {},
153
244
  ): TolerantTokens {
245
+ const { tokens, errors } = scan(source, options);
246
+ return { tokens, errors };
247
+ }
248
+
249
+ /**
250
+ * The tokens of tolerant tokenizing, the errors, and where the damage of
251
+ * each error starts: the tag that is malformed, which an error inside it
252
+ * (an attribute value) is after.
253
+ */
254
+ function scan(
255
+ source: string,
256
+ options: ParseMarkupOptions,
257
+ ): TolerantTokens & { damage: number[] } {
154
258
  const tokens: Token[] = [];
155
259
  const errors: MarkupError[] = [];
260
+ const damage: number[] = [];
156
261
  // The code of a tag ends at a }: with none after it, the tag is unclosed
157
262
  // without reading its code to the end of the source, which every
158
263
  // unclosed tag would do again (#265).
@@ -169,7 +274,7 @@ export function tokenizeMarkupTolerant(
169
274
  };
170
275
  try {
171
276
  return tokenizeMarkup(text, { ...options, hooks }).map((token) =>
172
- shift(token, base),
277
+ shiftOffsets(token, base),
173
278
  );
174
279
  } catch (error) {
175
280
  if (!(error instanceof MarkupError)) throw error;
@@ -186,7 +291,16 @@ export function tokenizeMarkupTolerant(
186
291
  }
187
292
  const at = base + result.offset;
188
293
  const { line, column } = lineColumn(source, at);
189
- errors.push(new MarkupError(result.reason, at, line, column));
294
+ errors.push(
295
+ new MarkupError(
296
+ result.reason,
297
+ at,
298
+ line,
299
+ column,
300
+ result.code,
301
+ base + result.end,
302
+ ),
303
+ );
190
304
  // The longest prefix that tokenizes: the error may be inside a tag
191
305
  // (an attribute value) of which the prefix is itself malformed
192
306
  let cut = result.offset;
@@ -196,6 +310,7 @@ export function tokenizeMarkupTolerant(
196
310
  prefix = attempt(rest.slice(0, cut), base);
197
311
  }
198
312
  tokens.push(...prefix);
313
+ damage.push(base + cut);
199
314
  // The character that started the damage is text
200
315
  if (cut < rest.length) {
201
316
  const start = base + cut;
@@ -208,16 +323,31 @@ export function tokenizeMarkupTolerant(
208
323
  }
209
324
  base += cut + 1;
210
325
  }
211
- return { tokens, errors };
326
+ return { tokens, errors, damage };
212
327
  }
213
328
 
214
- /** `token` with its offsets moved `by` on. */
215
- function shift(token: Token, by: number): Token {
216
- if (by === 0) return token;
217
- const moved = { ...token, start: token.start + by, end: token.end + by };
218
- if (moved.type === 'link') {
219
- moved.targetStart += by;
220
- moved.targetEnd += by;
329
+ /** The offset fields of a token (and of an attribute): `start`, `nameEnd`… */
330
+ const OFFSET_FIELD = /^(start|end|[A-Za-z]*(Start|End))$/;
331
+
332
+ /** `token` (or an attribute of it) with each of its offsets turned by `map`. */
333
+ export function mapOffsets<T extends object>(
334
+ token: T,
335
+ map: (offset: number) => number,
336
+ ): T {
337
+ const moved: Record<string, unknown> = {
338
+ ...(token as Record<string, unknown>),
339
+ };
340
+ for (const [key, value] of Object.entries(moved)) {
341
+ if (typeof value === 'number' && OFFSET_FIELD.test(key)) {
342
+ moved[key] = map(value);
343
+ } else if (key === 'attributeSpans') {
344
+ moved[key] = (value as object[]).map((span) => mapOffsets(span, map));
345
+ }
221
346
  }
222
- return moved;
347
+ return moved as T;
348
+ }
349
+
350
+ /** `token` (or an attribute of it) with its offsets moved `by` on. */
351
+ export function shiftOffsets<T extends object>(token: T, by: number): T {
352
+ return by === 0 ? token : mapOffsets(token, (offset) => offset + by);
223
353
  }
@@ -680,9 +680,14 @@ function resolveAttributeValue(
680
680
  return result.text;
681
681
  }
682
682
 
683
+ /** Whether a node shows nothing as text: whitespace, or a closed HTML comment. */
684
+ function isBlankText(n: ASTNode): boolean {
685
+ return n.type === 'text' && (n.comment === true || n.value.trim() === '');
686
+ }
687
+
683
688
  /** The index of the summary element opening `nodes`, or -1 when none does. */
684
689
  function leadingSummaryIndex(nodes: ASTNode[]): number {
685
- const at = nodes.findIndex((n) => n.type !== 'text' || n.value.trim() !== '');
690
+ const at = nodes.findIndex((n) => !isBlankText(n));
686
691
  const first = nodes[at];
687
692
  return first?.type === 'html' && first.tag.toLowerCase() === 'summary'
688
693
  ? at
@@ -719,7 +724,13 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
719
724
  let children: preact.ComponentChildren = undefined;
720
725
  let structural = false;
721
726
  if (node.children.length > 0) {
722
- if (inRaw || isRawRoot) {
727
+ if (tag === 'style') {
728
+ // A raw-text element: its CSS keeps character-reference lookalikes
729
+ // (`?a=1&notch=2`) as written (#453)
730
+ children = node.children.map((n) =>
731
+ n.type === 'text' ? n.value : renderSingleNode(n),
732
+ );
733
+ } else if (inRaw || isRawRoot) {
723
734
  children = renderInlineNodes(node.children);
724
735
  } else {
725
736
  // A details element's summary stays its direct child: it is rendered
@@ -730,7 +741,7 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
730
741
  renderNodes(nodes, { nobr, locals, inline: isInline });
731
742
  structural =
732
743
  STRUCTURAL_ELEMENTS.has(tag) &&
733
- node.children.every((n) => n.type !== 'text' || n.value.trim() === '');
744
+ node.children.every((n) => n.type !== 'text' || isBlankText(n));
734
745
  children = structural ? (
735
746
  node.children
736
747
  .filter((n) => n.type !== 'text')
@@ -1017,7 +1028,7 @@ export function renderNodes(
1017
1028
  // paragraphs would pull the elements they produce out of it (#436)
1018
1029
  if (
1019
1030
  options?.structural &&
1020
- nodes.every((n) => n.type !== 'text' || n.value.trim() === '')
1031
+ nodes.every((n) => n.type !== 'text' || isBlankText(n))
1021
1032
  ) {
1022
1033
  return nodes.filter((n) => n.type !== 'text').map(renderSingleNode);
1023
1034
  }
@@ -13,7 +13,7 @@ export declare class SyntaxError extends globalThis.SyntaxError {
13
13
  }
14
14
 
15
15
  export interface ParseOptions {
16
- startRule: 'Markup' | 'Tokens' | 'SelectorsPrefix';
16
+ startRule: 'Tokens' | 'SelectorsPrefix';
17
17
  /** Text mode (attribute values, labels). */
18
18
  text: boolean;
19
19
  /** What the grammar leaves to code (see parse.ts MarkupHooks). */
@@ -21,7 +21,7 @@ export interface ParseOptions {
21
21
  }
22
22
 
23
23
  /**
24
- * Parse markup: the AST for `Markup`, the tokens for `Tokens`, the selectors
25
- * and where they end for `SelectorsPrefix`.
24
+ * Parse markup: the tokens for `Tokens`, the selectors and where they end for
25
+ * `SelectorsPrefix`.
26
26
  */
27
27
  export declare function parse(input: string, options: ParseOptions): unknown;