@popcorn245/cornfield 0.51.0 → 0.51.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popcorn245/cornfield",
3
- "version": "0.51.0",
3
+ "version": "0.51.2",
4
4
  "description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
5
5
  "license": "MIT",
6
6
  "author": "popcorn245 (https://github.com/popcorn245)",
@@ -18,116 +18,367 @@ const ALLOWED_TAGS = {
18
18
  details: ['open'], summary: [], sub: [], sup: [], kbd: [], b: [], i: [], em: [], strong: [], code: [], a: ['href', 'title'],
19
19
  };
20
20
  const VOID_TAGS = new Set(['img', 'br', 'hr']);
21
- /** An href or src the page may keep: http(s), mailto, or a relative or anchor link */
22
- const safeUrl = (u) => (typeof u === 'string' && (/^(https?:|mailto:)/i.test(u) || !/^[a-z][a-z0-9+.-]*:/i.test(u.trim())) ? u : null);
21
+ const WEB_URL = /^(https?:|mailto:)/i;
22
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/i;
23
+ /**
24
+ * An href or src the page may keep: http(s), mailto, or a relative or anchor link. Checked also as a browser reads
25
+ * it, which drops every tab and newline and any control or space at the start, so `java\tscript:` is `javascript:`.
26
+ */
27
+ const safeUrl = (u) => {
28
+ if (typeof u !== 'string') return null;
29
+ const read = u.replace(/[\t\n\r]/g, '').replace(/^[\u0000- ]+/, '');
30
+ return (WEB_URL.test(u) || !SCHEME.test(u.trim())) && (WEB_URL.test(read) || !SCHEME.test(read)) ? u : null;
31
+ };
23
32
 
24
33
  /**
25
34
  * The anchor GitHub gives a heading: lower case, punctuation dropped, spaces to hyphens.
26
35
  * @param {string} text the heading's plain text
27
36
  */
28
37
  export function slugify(text) {
29
- return text.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
38
+ // Letters keep their marks (the vowel signs of Devanagari, a decomposed \u00e9); only a plain space becomes a hyphen,
39
+ // so a no-break space or a tab is dropped, as GitHub drops it
40
+ return text.toLowerCase().replace(/[^\p{L}\p{M}\p{N}_ -]/gu, '').replace(/ /g, '-');
41
+ }
42
+
43
+ const NAMED_ENTITIES = {
44
+ lt: '<', gt: '>', amp: '&', quot: '"', apos: "'", nbsp: '\u00a0', copy: '\u00a9', reg: '\u00ae', trade: '\u2122', hellip: '\u2026',
45
+ mdash: '\u2014', ndash: '\u2013', middot: '\u00b7', bull: '\u2022', times: '\u00d7', deg: '\u00b0', laquo: '\u00ab', raquo: '\u00bb',
46
+ lsquo: '\u2018', rsquo: '\u2019', ldquo: '\u201c', rdquo: '\u201d', larr: '\u2190', rarr: '\u2192', uarr: '\u2191', darr: '\u2193', harr: '\u2194',
47
+ };
48
+
49
+ /** A character reference's text (`&lt;`, `&#60;`, `&#x3c;`); one this does not know stays as written */
50
+ const decodeEntities = (s) => s.replace(/&(?:#(\d{1,7})|#[xX]([0-9a-fA-F]{1,6})|([a-zA-Z]+));/g, (all, dec, hex, name) => {
51
+ if (name) return NAMED_ENTITIES[name] ?? all;
52
+ const cp = dec ? Number(dec) : parseInt(hex, 16);
53
+ return cp > 0 && cp <= 0x10ffff && !(cp >= 0xd800 && cp <= 0xdfff) ? String.fromCodePoint(cp) : all;
54
+ });
55
+
56
+ const WORD = /[\p{L}\p{N}]/u;
57
+ const isWordAt = (s, i) => i >= 0 && i < s.length && WORD.test(String.fromCodePoint(s.codePointAt(i)));
58
+ const isWordBefore = (s, i) => isWordAt(s, i >= 2 && /[\udc00-\udfff]/.test(s[i - 1]) && /[\ud800-\udbff]/.test(s[i - 2]) ? i - 2 : i - 1);
59
+ const PUNCT = /[!-/:-@[-`{-~]/;
60
+
61
+ /**
62
+ * Backslash escapes and code spans, in one pass from the left as CommonMark reads them: an escaped mark and a code
63
+ * span's text are handed to `keep` (a backslash inside code is literal), an unmatched run of backticks is text.
64
+ * Linear: a run is closed by the next run of the same length, found from the runs listed once.
65
+ */
66
+ function codeAndEscapes(s, keep) {
67
+ const runs = new Map();
68
+ for (const m of s.matchAll(/`+/g)) {
69
+ if (!runs.has(m[0].length)) runs.set(m[0].length, { at: [], next: 0 });
70
+ runs.get(m[0].length).at.push(m.index);
71
+ }
72
+ let out = '';
73
+ let i = 0;
74
+ while (i < s.length) {
75
+ const c = s[i];
76
+ if (c === '\\' && PUNCT.test(s[i + 1] || '')) { out += keep(s[i + 1]); i += 2; continue; }
77
+ if (c !== '`') { out += c; i++; continue; }
78
+ let n = 1;
79
+ while (s[i + n] === '`') n++;
80
+ const same = runs.get(n);
81
+ // A run that starts after an escaped backtick is not in the list (it is shorter than the run it is part of)
82
+ while (same && same.next < same.at.length && same.at[same.next] < i + n) same.next++;
83
+ const close = same && same.next < same.at.length ? same.at[same.next] : -1;
84
+ if (close < 0) { out += s.slice(i, i + n); i += n; continue; }
85
+ const code = s.slice(i + n, close).replace(/\n/g, ' ');
86
+ out += keep(/^ .*[^ ].* $/s.test(code) ? code.slice(1, -1) : code);
87
+ i = close + n;
88
+ }
89
+ return out;
90
+ }
91
+
92
+ /** Each `<!-- … -->` taken out (linear: once one has no end, no later one has) */
93
+ function dropComments(s) {
94
+ let out = '';
95
+ let i = 0;
96
+ for (;;) {
97
+ const open = s.indexOf('<!--', i);
98
+ const close = open < 0 ? -1 : s.indexOf('-->', open + 4);
99
+ if (close < 0) return out + s.slice(i);
100
+ out += s.slice(i, open);
101
+ i = close + 3;
102
+ }
30
103
  }
31
104
 
32
- /** A heading's or link text's plain words: the Markdown marks taken out */
105
+ /**
106
+ * `_em_` and `__strong__` as their text: a mark opens only where no letter or digit is before it and closes only
107
+ * where none is after it, so `snake_case_name` keeps its underscores. Linear: the next closing mark from each
108
+ * place is worked out once, from the right.
109
+ */
110
+ function dropUnderscores(s) {
111
+ const n = s.length;
112
+ const close1 = new Int32Array(n + 3).fill(-1);
113
+ const close2 = new Int32Array(n + 3).fill(-1);
114
+ const newline = new Int32Array(n + 3).fill(-1);
115
+ for (let p = n - 1; p >= 0; p--) {
116
+ close1[p] = s[p] === '_' && !isWordAt(s, p + 1) ? p : close1[p + 1];
117
+ close2[p] = s[p] === '_' && s[p + 1] === '_' && !isWordAt(s, p + 2) ? p : close2[p + 1];
118
+ newline[p] = s[p] === '\n' ? p : newline[p + 1];
119
+ }
120
+ let out = '';
121
+ let i = 0;
122
+ outer: while (i < n) {
123
+ if (s[i] === '_' && !isWordBefore(s, i)) {
124
+ for (const mark of s[i + 1] === '_' ? [2, 1] : [1]) {
125
+ const start = i + mark;
126
+ if (start >= n || /\s/u.test(s[start])) continue;
127
+ const end = (mark === 2 ? close2 : close1)[start + 1];
128
+ if (end < 0 || (newline[start] >= 0 && newline[start] < end)) continue;
129
+ out += s.slice(start, end);
130
+ i = end + mark;
131
+ continue outer;
132
+ }
133
+ }
134
+ out += s[i];
135
+ i++;
136
+ }
137
+ return out;
138
+ }
139
+
140
+ /**
141
+ * The text a heading or link text renders to, the way GitHub reads it before it makes a heading's anchor, untrimmed:
142
+ * a code span keeps its literal text (so `<tag>` in backticks stays, brackets and all), a real inline HTML tag
143
+ * outside code gives only its inner text, emphasis and links give their text, an autolink its address, and a
144
+ * character reference is its character. An image gives its alt text, or nothing with `images: false` (GitHub's
145
+ * anchor reads the heading's text, and an image has none).
146
+ */
147
+ function inlineText(src, { images = true } = {}) {
148
+ // What must reach the end as written (code spans, escaped marks, autolinks) is set aside first, so no later step
149
+ // reads it. A NUL in the source is U+FFFD (as CommonMark has it), so the source cannot forge a set-aside mark.
150
+ const kept = [];
151
+ const keep = (t) => `\u0000${kept.push(t) - 1}\u0000`;
152
+ let s = codeAndEscapes(String(src).replace(/\u0000/g, '�'), keep);
153
+ s = s.replace(/<((?:https?:\/\/|mailto:)[^\s<>]+)>/gi, (_, url) => keep(url.replace(/^mailto:/i, '')));
154
+ // A link or image: `[text](dest "title")`; the spaces are matched so that no two runs of them can trade places
155
+ s = s.replace(/(!?)\[([^[\]]*)\]\(\s*(?:(?:<[^<>\n]*>|(?:[^()\s]|\([^()\s]*\))+)(?:\s+(?:"[^"]*"|'[^']*'|\([^()]*\)))?\s*|(?:"[^"]*"|'[^']*')\s*)?\)/g, (_, bang, text) => (bang && !images ? '' : text));
156
+ s = dropComments(s).replace(/<\/?[a-zA-Z][^<>]*>/g, '').replace(/(\*\*|\*)(?=\S)(.+?)\1/g, '$2');
157
+ return decodeEntities(dropUnderscores(s)).replace(/\u0000(\d+)\u0000/g, (_, k) => kept[k]);
158
+ }
159
+
160
+ /** A heading's or link text's plain words (see inlineText), trimmed */
33
161
  export function plainText(src) {
34
- return src
35
- .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
36
- .replace(/`+([^`]*)`+/g, '$1')
37
- .replace(/(\*\*|__|\*|_)(.+?)\1/g, '$2')
38
- .replace(/<[^>]+>/g, '')
39
- .replace(/\\(.)/g, '$1')
40
- .trim();
162
+ return inlineText(src).trim();
41
163
  }
42
164
 
165
+ /** A heading's anchor before it is numbered: from its text as GitHub reads it, images giving nothing, untrimmed */
166
+ const headingSlug = (src) => slugify(inlineText(src, { images: false }));
167
+
43
168
  // ---------------------------------------------------------------------------
44
169
  // Inline
45
170
  // ---------------------------------------------------------------------------
46
171
 
47
- /** The `[text](dest "title")` starting at `i` (src[i] === '['), or null */
48
- function parseLink(src, i) {
49
- let depth = 0;
50
- let j = i;
51
- for (; j < src.length; j++) {
52
- const c = src[j];
53
- if (c === '\\') { j++; continue; }
54
- if (c === '`') {
55
- const run = /^`+/.exec(src.slice(j))[0];
56
- const close = src.indexOf(run, j + run.length);
57
- if (close > 0) { j = close + run.length - 1; continue; }
172
+ /**
173
+ * The deepest a link or emphasis may sit inside another, and a list or quote inside another: each level reads its
174
+ * text again, so deeper marks stay as written (and no crafted line can run the reader out of stack)
175
+ */
176
+ const MAX_NEST = 16;
177
+
178
+ /**
179
+ * What a line's links and code spans need, each worked out once, from the right, so that no failed match makes a
180
+ * later one look ahead to the end of the line again:
181
+ * - `up[x]`: the first `]` after x that is not matched by a `[` after x (or -1), reading as a link's text is read: an
182
+ * escaped character and a code span (a run of backticks up to the next run at least as long) are stepped over whole.
183
+ * For a `[` at x, that is the `]` which closes it;
184
+ * - `kRun[x]`: for a run of backticks that starts (or, after an escape, continues) at x, the next run after it at
185
+ * least as long, which a code span may close on (or -1).
186
+ * The next run at least that long is found among the runs after the one being passed, kept as a stack in which each
187
+ * is longer than every one nearer to it, so it is a binary search.
188
+ */
189
+ function scanIndex(src) {
190
+ const n = src.length;
191
+ const rs = [];
192
+ const re = [];
193
+ for (let p = 0; p < n; p++) {
194
+ if (src.charCodeAt(p) !== 96) continue;
195
+ let q = p + 1;
196
+ while (src.charCodeAt(q) === 96) q++;
197
+ rs.push(p);
198
+ re.push(q);
199
+ p = q - 1;
200
+ }
201
+ const up = new Int32Array(n + 1).fill(-1);
202
+ const kRun = new Int32Array(n + 1).fill(-1);
203
+ const stack = []; // runs after the one passed, the nearest last; each longer than all nearer ones
204
+ // The last of the stack with a length of at least m (there is one when m is at most the longest)
205
+ const nearest = (m) => {
206
+ let lo = 0;
207
+ let hi = stack.length - 1;
208
+ while (lo < hi) {
209
+ const mid = (lo + hi + 1) >> 1;
210
+ if (re[stack[mid]] - rs[stack[mid]] >= m) lo = mid; else hi = mid - 1;
211
+ }
212
+ return stack[lo];
213
+ };
214
+ let r = rs.length - 1;
215
+ for (let x = n - 1; x >= 0; x--) {
216
+ const c = src.charCodeAt(x);
217
+ let next = x + 1; // where the bracket scan goes on from x
218
+ if (c === 92) next = Math.min(x + 2, n);
219
+ else if (c === 96) {
220
+ const len = re[r] - x;
221
+ const longest = stack.length ? re[stack[0]] - rs[stack[0]] : 0;
222
+ if (!longest) next = re[r];
223
+ else {
224
+ // A code span that finds no end gives the scan one character on, and the run one shorter to try; so the scan
225
+ // lands after the nearest run that is as long as the longest it can use
226
+ const use = Math.min(len, longest);
227
+ const k = nearest(use);
228
+ next = rs[k] + use;
229
+ if (len <= longest) kRun[x] = k;
230
+ }
231
+ }
232
+ // From `next`: a `]` is the answer; a `[` opens a pair of its own, closed at up[next], and the scan goes on after
233
+ // that `]` (which up[] at the `]` gives); anything else, the scan goes on from it
234
+ const cn = next < n ? src.charCodeAt(next) : 0;
235
+ if (next >= n) up[x] = -1;
236
+ else if (cn === 93) up[x] = next;
237
+ else if (cn === 91) up[x] = up[next] < 0 ? -1 : up[up[next]];
238
+ else up[x] = up[next];
239
+ if (c === 96 && x === rs[r]) {
240
+ while (stack.length && re[stack[stack.length - 1]] - rs[stack[stack.length - 1]] <= re[r] - rs[r]) stack.pop();
241
+ stack.push(r--);
58
242
  }
59
- if (c === '[') depth++;
60
- else if (c === ']' && --depth === 0) break;
61
243
  }
62
- if (depth !== 0 || src[j + 1] !== '(') return null;
244
+ return { up, kRun, rs, re };
245
+ }
246
+
247
+ /** For the ends of a link, each a table over the places in the line, worked out once from the right (see parseLink) */
248
+ function linkTables(src) {
249
+ const n = src.length;
250
+ const skip = new Int32Array(n + 3); // the first place at or after x that is not a space
251
+ const gt = new Int32Array(n + 3).fill(-1); // the next `>`
252
+ const dq = new Int32Array(n + 3).fill(-1); // the next `"`
253
+ const sq = new Int32Array(n + 3).fill(-1); // the next `'`
254
+ const stop = new Int32Array(n + 3); // where a bare destination read from x ends
255
+ for (let x = n; x < n + 3; x++) { skip[x] = x; stop[x] = n; }
256
+ for (let x = n - 1; x >= 0; x--) {
257
+ const c = src.charCodeAt(x);
258
+ skip[x] = c === 32 ? skip[x + 1] : x;
259
+ gt[x] = c === 62 ? x : gt[x + 1];
260
+ dq[x] = c === 34 ? x : dq[x + 1];
261
+ sq[x] = c === 39 ? x : sq[x + 1];
262
+ if (c === 92 && x + 1 < n) stop[x] = stop[x + 2]; // an escaped character is stepped over
263
+ else if (c === 32 || c === 41) stop[x] = x; // a space, or a `)` that closes no `(` of the destination
264
+ else if (c === 40) {
265
+ // A `(` is closed by the first `)` its own text leaves unclosed; the destination goes on after that
266
+ const m = stop[x + 1];
267
+ stop[x] = m >= n || src.charCodeAt(m) === 32 ? m : stop[m + 1];
268
+ } else stop[x] = stop[x + 1];
269
+ }
270
+ return { skip, gt, dq, sq, stop };
271
+ }
272
+
273
+ /**
274
+ * The `[text](dest "title")` starting at `i` (src[i] === '['), or null. `index` and `tables` give what scanIndex and
275
+ * linkTables worked out for `src`, each built when first asked for.
276
+ */
277
+ function parseLink(src, i, index, tables) {
278
+ const j = index().up[i];
279
+ if (j < 0 || src[j + 1] !== '(') return null;
280
+ const t = tables();
63
281
  const text = src.slice(i + 1, j);
64
- let k = j + 2;
65
- while (src[k] === ' ') k++;
66
- let dest = '';
282
+ let k = t.skip[j + 2];
283
+ let dest;
284
+ let bare = -1;
67
285
  if (src[k] === '<') {
68
- const close = src.indexOf('>', k);
286
+ const close = t.gt[k];
69
287
  if (close < 0) return null;
70
288
  dest = src.slice(k + 1, close);
71
289
  k = close + 1;
72
290
  } else {
73
- let parens = 0;
74
- for (; k < src.length; k++) {
75
- const c = src[k];
76
- if (c === '\\' && k + 1 < src.length) { dest += src[++k]; continue; }
77
- if (c === ' ' || (c === ')' && parens === 0)) break;
78
- if (c === '(') parens++;
79
- if (c === ')') parens--;
80
- dest += c;
81
- }
291
+ bare = k;
292
+ k = t.stop[k];
82
293
  }
83
- while (src[k] === ' ') k++;
294
+ const destEnd = k;
295
+ k = t.skip[k];
84
296
  let title = null;
85
297
  const quote = src[k];
86
298
  if (quote === '"' || quote === "'") {
87
- const close = src.indexOf(quote, k + 1);
299
+ const close = (quote === '"' ? t.dq : t.sq)[k + 1];
88
300
  if (close < 0) return null;
89
301
  title = src.slice(k + 1, close);
90
- k = close + 1;
91
- while (src[k] === ' ') k++;
302
+ k = t.skip[close + 1];
92
303
  }
93
304
  if (src[k] !== ')') return null;
305
+ if (bare >= 0) {
306
+ dest = '';
307
+ for (let p = bare; p < destEnd; p++) {
308
+ if (src[p] === '\\' && p + 1 < src.length) p++;
309
+ dest += src[p];
310
+ }
311
+ }
94
312
  return { text, dest, title, end: k + 1 };
95
313
  }
96
314
 
97
315
  const isWordChar = (c) => c !== undefined && /[\p{L}\p{N}]/u.test(c);
98
316
 
99
317
  /**
100
- * One line (or a paragraph's lines) of inline Markdown as HTML.
318
+ * Where the mark that opens at some place is closed (`close[from]`, or -1), for a mark of one character or two, from
319
+ * the place the search starts: the first mark from there that has no space before it, is not (for `_`) followed by a
320
+ * letter or digit, and (for one character) is not the first of two. A pair is stepped over whole.
321
+ */
322
+ function closers(src, c, strong) {
323
+ const n = src.length;
324
+ const close = new Int32Array(n + 4).fill(-1);
325
+ for (let q = n - 1; q >= 0; q--) {
326
+ if (src[q] !== c || (strong && src[q + 1] !== c)) close[q] = close[q + 1];
327
+ else if (!strong && src[q + 1] === c) close[q] = close[q + 2];
328
+ else close[q] = /\s/.test(src[q - 1]) || (c === '_' && isWordChar(src[q + (strong ? 2 : 1)])) ? close[q + 1] : q;
329
+ }
330
+ return close;
331
+ }
332
+
333
+ const AUTOLINK = /<((?:https?:\/\/|mailto:)[^\s<>]+)>/iy;
334
+
335
+ /**
336
+ * One line (or a paragraph's lines) of inline Markdown as HTML. Linear in the length of the line (times the depth
337
+ * to which marks sit inside one another, at most MAX_NEST).
101
338
  * @param {string} src
102
339
  * @param {{ link: Function }} ctx
103
340
  */
104
341
  export function renderInline(src, ctx) {
342
+ return inline(src, ctx, 0);
343
+ }
344
+
345
+ function inline(src, ctx, depth) {
346
+ let ix = null;
347
+ let lt = null;
348
+ const index = () => (ix ??= scanIndex(src));
349
+ const tables = () => (lt ??= linkTables(src));
350
+ const marks = {};
351
+ let linkAt = -1; // the link parsed at this place, for the image attempt and then the link attempt at the same `[`
352
+ let link = null;
105
353
  let out = '';
106
354
  let i = 0;
107
355
  while (i < src.length) {
108
356
  const c = src[i];
109
357
  if (c === '\\' && /[!-/:-@[-`{-~]/.test(src[i + 1] || '')) { out += esc(src[i + 1]); i += 2; continue; }
110
358
  if (c === '\n') {
111
- out += / $/.test(src.slice(0, i)) ? '<br>\n' : '\n';
359
+ out += i >= 2 && src[i - 1] === ' ' && src[i - 2] === ' ' ? '<br>\n' : '\n';
112
360
  i++;
113
361
  continue;
114
362
  }
115
363
  if (c === '`') {
116
- const run = /^`+/.exec(src.slice(i))[0];
117
- const close = src.indexOf(run, i + run.length);
118
- if (close > 0 && src[close + run.length] !== '`') {
119
- let code = src.slice(i + run.length, close).replace(/\n/g, ' ');
364
+ const { kRun, rs, re } = index();
365
+ let n = 1;
366
+ while (src[i + n] === '`') n++;
367
+ const k = kRun[i];
368
+ if (k >= 0 && re[k] - rs[k] === n) {
369
+ let code = src.slice(i + n, rs[k]).replace(/\n/g, ' ');
120
370
  if (/^ .* $/.test(code)) code = code.slice(1, -1);
121
371
  out += `<code>${esc(code)}</code>`;
122
- i = close + run.length;
372
+ i = re[k];
123
373
  continue;
124
374
  }
125
- out += esc(run);
126
- i += run.length;
375
+ out += esc(src.slice(i, i + n));
376
+ i += n;
127
377
  continue;
128
378
  }
129
379
  if (c === '!' && src[i + 1] === '[') {
130
- const l = parseLink(src, i + 1);
380
+ if (linkAt !== i + 1) { link = parseLink(src, i + 1, index, tables); linkAt = i + 1; }
381
+ const l = link;
131
382
  if (l) {
132
383
  const href = safeUrl(ctx.link(l.dest, { image: true }));
133
384
  const alt = plainText(l.text);
@@ -136,44 +387,37 @@ export function renderInline(src, ctx) {
136
387
  continue;
137
388
  }
138
389
  }
139
- if (c === '[') {
140
- const l = parseLink(src, i);
390
+ if (c === '[' && depth < MAX_NEST) {
391
+ if (linkAt !== i) { link = parseLink(src, i, index, tables); linkAt = i; }
392
+ const l = link;
141
393
  if (l) {
142
394
  const href = safeUrl(ctx.link(l.dest, { image: false }));
143
- const inner = renderInline(l.text, ctx);
395
+ const inner = inline(l.text, ctx, depth + 1);
144
396
  out += href ? `<a href="${esc(href)}"${l.title ? ` title="${esc(l.title)}"` : ''}>${inner}</a>` : inner;
145
397
  i = l.end;
146
398
  continue;
147
399
  }
148
400
  }
149
401
  if (c === '<') {
150
- const auto = /^<((?:https?:\/\/|mailto:)[^\s<>]+)>/i.exec(src.slice(i));
402
+ AUTOLINK.lastIndex = i;
403
+ const auto = AUTOLINK.exec(src);
151
404
  if (auto) {
152
405
  out += `<a href="${esc(auto[1])}">${esc(auto[1].replace(/^mailto:/i, ''))}</a>`;
153
406
  i += auto[0].length;
154
407
  continue;
155
408
  }
156
409
  }
157
- if (c === '*' || c === '_') {
410
+ if ((c === '*' || c === '_') && depth < MAX_NEST) {
158
411
  const strong = src[i + 1] === c;
159
- const mark = strong ? c + c : c;
160
- const opens = !/\s/.test(src[i + mark.length] || ' ') && (c === '*' || !isWordChar(src[i - 1]));
412
+ const size = strong ? 2 : 1;
413
+ const opens = !/\s/.test(src[i + size] || ' ') && (c === '*' || !isWordChar(src[i - 1]));
161
414
  if (opens) {
162
- let close = i + mark.length;
163
- for (;;) {
164
- close = src.indexOf(mark, close + 1);
165
- if (close < 0) break;
166
- const before = src[close - 1];
167
- const after = src[close + mark.length];
168
- // `**` must not be read as the end of a `*` run, and `_` closes only at a word's end
169
- if (!strong && src[close + 1] === c) { close++; continue; }
170
- if (/\s/.test(before) || (c === '_' && isWordChar(after))) continue;
171
- break;
172
- }
173
- if (close > i + mark.length) {
415
+ // `**` is not the end of a `*` run, and `_` closes only at a word's end (see closers)
416
+ const close = (marks[c + size] ??= closers(src, c, strong))[i + size + 1];
417
+ if (close >= 0) {
174
418
  const tag = strong ? 'strong' : 'em';
175
- out += `<${tag}>${renderInline(src.slice(i + mark.length, close), ctx)}</${tag}>`;
176
- i = close + mark.length;
419
+ out += `<${tag}>${inline(src.slice(i + size, close), ctx, depth + 1)}</${tag}>`;
420
+ i = close + size;
177
421
  continue;
178
422
  }
179
423
  }
@@ -188,21 +432,108 @@ export function renderInline(src, ctx) {
188
432
  // HTML blocks
189
433
  // ---------------------------------------------------------------------------
190
434
 
435
+ const isSpaceCode = (c, ch) => c === 32 || (c >= 9 && c <= 13) || (c >= 128 && /\s/.test(ch));
436
+
437
+ /**
438
+ * The tags and comments of an HTML block, as `/<(\/?)([a-zA-Z][\w-]*)((?:\s+[^\s=>/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|<!--[\s\S]*?-->/g`
439
+ * finds them, but in linear time (that expression starts again at every `<` and reads to the end of the block each
440
+ * time). A tag's attributes are read the one way the expression can read them (it has no other that matches), and
441
+ * where the rest of the attributes lead from a place is worked out once; a comment's end is looked for once.
442
+ * @returns {{ index: number, end: number, closing: string, tag: string, attrs: string, comment: boolean }[]}
443
+ */
444
+ function* htmlTokens(src) {
445
+ const n = src.length;
446
+ let tables = null;
447
+ const build = () => {
448
+ // From each place: the next that is not a space, not a name's character, not an unquoted value's; the next quote
449
+ const skip = new Int32Array(n + 2);
450
+ const name = new Int32Array(n + 2);
451
+ const bare = new Int32Array(n + 2);
452
+ skip[n] = skip[n + 1] = name[n] = name[n + 1] = bare[n] = bare[n + 1] = n;
453
+ for (let x = n - 1; x >= 0; x--) {
454
+ const ch = src[x];
455
+ const c = src.charCodeAt(x);
456
+ const space = isSpaceCode(c, ch);
457
+ skip[x] = space ? skip[x + 1] : x;
458
+ name[x] = space || ch === '=' || ch === '>' || ch === '/' ? x : name[x + 1];
459
+ bare[x] = space || ch === '"' || ch === "'" || ch === '=' || ch === '<' || ch === '>' || ch === '`' ? x : bare[x + 1];
460
+ }
461
+ return { skip, name, bare, memo: new Int32Array(n + 2).fill(-2) };
462
+ };
463
+ // Where the attributes that can be read from q end (the place after the last), or -1 when they lead to no `>`
464
+ const attrsEnd = (q0) => {
465
+ const { skip, name, bare, memo } = (tables ??= build());
466
+ const seen = [];
467
+ let q = q0;
468
+ let result;
469
+ for (;;) {
470
+ if (memo[q] !== -2) { result = memo[q]; break; }
471
+ seen.push(q);
472
+ const w = skip[q];
473
+ if (w > q && w < n && name[w] > w) {
474
+ const e = name[w];
475
+ const z = skip[e];
476
+ if (src[z] !== '=') { q = e; continue; }
477
+ const v = skip[z + 1];
478
+ let vEnd = -1;
479
+ if (src[v] === '"' || src[v] === "'") {
480
+ const close = src.indexOf(src[v], v + 1);
481
+ if (close >= 0) vEnd = close + 1;
482
+ } else if (bare[v] > v) vEnd = bare[v];
483
+ if (vEnd < 0) { result = -1; break; }
484
+ q = vEnd;
485
+ continue;
486
+ }
487
+ // No more attributes: a `>`, or a `/` and then a `>`, after any spaces
488
+ result = src[w] === '>' || (src[w] === '/' && src[w + 1] === '>') ? q : -1;
489
+ break;
490
+ }
491
+ for (const x of seen) tables.memo[x] = result;
492
+ return result;
493
+ };
494
+ const head = /<(\/?)([a-zA-Z][\w-]*)/y;
495
+ let noCommentEnd = false;
496
+ let p = src.indexOf('<');
497
+ while (p >= 0) {
498
+ head.lastIndex = p;
499
+ const m = head.exec(src);
500
+ if (m) {
501
+ const e = p + m[0].length;
502
+ const a = attrsEnd(e);
503
+ if (a >= 0) {
504
+ const w = tables.skip[a];
505
+ const end = (src[w] === '/' ? w + 1 : w) + 1;
506
+ yield { index: p, end, closing: m[1], tag: m[2], attrs: src.slice(e, a), comment: false };
507
+ p = src.indexOf('<', end);
508
+ continue;
509
+ }
510
+ } else if (!noCommentEnd && src.startsWith('<!--', p)) {
511
+ const close = src.indexOf('-->', p + 4);
512
+ if (close < 0) noCommentEnd = true; // no later `<!--` has an end either
513
+ else {
514
+ yield { index: p, end: close + 3, comment: true };
515
+ p = src.indexOf('<', close + 3);
516
+ continue;
517
+ }
518
+ }
519
+ p = src.indexOf('<', p + 1);
520
+ }
521
+ }
522
+
191
523
  /** An HTML block with only the allowed tags and attributes kept; every other tag dropped, the text escaped */
192
524
  function sanitizeHtml(src, ctx) {
193
525
  let out = '';
194
526
  let last = 0;
195
- const tagRe = /<(\/?)([a-zA-Z][\w-]*)((?:\s+[^\s=>/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|<!--[\s\S]*?-->/g;
196
- for (const m of src.matchAll(tagRe)) {
527
+ for (const m of htmlTokens(src)) {
197
528
  out += esc(src.slice(last, m.index));
198
- last = m.index + m[0].length;
199
- if (!m[2]) continue; // a comment
200
- const tag = m[2].toLowerCase();
529
+ last = m.end;
530
+ if (m.comment) continue;
531
+ const tag = m.tag.toLowerCase();
201
532
  const allowed = ALLOWED_TAGS[tag];
202
533
  if (!allowed) continue;
203
- if (m[1]) { if (!VOID_TAGS.has(tag)) out += `</${tag}>`; continue; }
534
+ if (m.closing) { if (!VOID_TAGS.has(tag)) out += `</${tag}>`; continue; }
204
535
  let attrs = '';
205
- for (const a of m[3].matchAll(/([^\s=>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g)) {
536
+ for (const a of m.attrs.matchAll(/([^\s=>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g)) {
206
537
  const name = a[1].toLowerCase();
207
538
  if (!allowed.includes(name)) continue;
208
539
  let value = a[2] ?? a[3] ?? a[4] ?? '';
@@ -221,7 +552,16 @@ function sanitizeHtml(src, ctx) {
221
552
  // Blocks
222
553
  // ---------------------------------------------------------------------------
223
554
 
224
- const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^`\s]*)[^`]*$/;
555
+ const FENCE_MARK = /^ {0,3}(`{3,}|~{3,})/;
556
+ /**
557
+ * A fence line's `[line, mark, info word]`, or null: the mark, then no backtick in the rest of the line. (Checked
558
+ * once; a single expression for it, `/^ {0,3}(`{3,}|~{3,})\s*([^`\s]*)[^`]*$/`, reads a long run of spaces again from each one.)
559
+ */
560
+ function fenceOf(line) {
561
+ const m = FENCE_MARK.exec(line);
562
+ if (!m || line.includes('`', m[0].length)) return null;
563
+ return [line, m[1], /^\s*([^`\s]*)/.exec(line.slice(m[0].length))[1]];
564
+ }
225
565
  const HEADING = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
226
566
  const RULE = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
227
567
  const QUOTE = /^ {0,3}> ?/;
@@ -252,22 +592,23 @@ function cells(line) {
252
592
  }
253
593
 
254
594
  /** Whether a line starts a block other than a paragraph (it interrupts a paragraph) */
255
- const startsBlock = (line) => FENCE.test(line) || HEADING.test(line) || RULE.test(line) || QUOTE.test(line) || HTML_START.test(line) || (LIST_ITEM.test(line) && !isBlank(LIST_ITEM.exec(line)[4]));
595
+ const startsBlock = (line) => fenceOf(line) || HEADING.test(line) || RULE.test(line) || QUOTE.test(line) || HTML_START.test(line) || (LIST_ITEM.test(line) && !isBlank(LIST_ITEM.exec(line)[4]));
256
596
 
257
597
  /**
258
598
  * Lines of Markdown as HTML.
259
599
  * @param {string[]} lines
260
600
  * @param {{ link: Function, headings: object[], slugs: Map<string, number> }} ctx
261
601
  * @param {boolean} [tight] paragraphs without <p> (a tight list item)
602
+ * @param {number} [depth] how many lists and quotes these lines sit in (from MAX_NEST on, a list or quote is text)
262
603
  */
263
- function renderBlocks(lines, ctx, tight = false) {
604
+ function renderBlocks(lines, ctx, tight = false, depth = 0) {
264
605
  const out = [];
265
606
  let i = 0;
266
607
  while (i < lines.length) {
267
608
  const line = lines[i];
268
609
  if (isBlank(line)) { i++; continue; }
269
610
 
270
- const fence = FENCE.exec(line);
611
+ const fence = fenceOf(line);
271
612
  if (fence) {
272
613
  const [, mark, lang] = fence;
273
614
  const indent = indentOf(line);
@@ -286,7 +627,7 @@ function renderBlocks(lines, ctx, tight = false) {
286
627
  if (heading) {
287
628
  const level = heading[1].length;
288
629
  const text = heading[2] || '';
289
- const base = slugify(plainText(text));
630
+ const base = headingSlug(text);
290
631
  const n = ctx.slugs.get(base) || 0;
291
632
  ctx.slugs.set(base, n + 1);
292
633
  const id = n ? `${base}-${n}` : base;
@@ -298,10 +639,10 @@ function renderBlocks(lines, ctx, tight = false) {
298
639
 
299
640
  if (RULE.test(line)) { out.push('<hr>'); i++; continue; }
300
641
 
301
- if (QUOTE.test(line)) {
642
+ if (QUOTE.test(line) && depth < MAX_NEST) {
302
643
  const body = [];
303
644
  while (i < lines.length && !isBlank(lines[i]) && (QUOTE.test(lines[i]) || !startsBlock(lines[i]))) body.push(lines[i++].replace(QUOTE, ''));
304
- out.push(`<blockquote>\n${renderBlocks(body, ctx)}\n</blockquote>`);
645
+ out.push(`<blockquote>\n${renderBlocks(body, ctx, false, depth + 1)}\n</blockquote>`);
305
646
  continue;
306
647
  }
307
648
 
@@ -326,7 +667,7 @@ function renderBlocks(lines, ctx, tight = false) {
326
667
  continue;
327
668
  }
328
669
 
329
- const item = LIST_ITEM.exec(line);
670
+ const item = depth < MAX_NEST && LIST_ITEM.exec(line);
330
671
  if (item) {
331
672
  const ordered = /\d/.test(item[2]);
332
673
  const kind = ordered ? item[2].slice(-1) : item[2];
@@ -359,7 +700,7 @@ function renderBlocks(lines, ctx, tight = false) {
359
700
  items.push(body);
360
701
  }
361
702
  const tag = ordered ? 'ol' : 'ul';
362
- const lis = items.map((b) => `<li>${renderBlocks(b, ctx, !loose)}</li>`).join('\n');
703
+ const lis = items.map((b) => `<li>${renderBlocks(b, ctx, !loose, depth + 1)}</li>`).join('\n');
363
704
  out.push(`<${tag}${ordered && start !== 1 ? ` start="${start}"` : ''}>\n${lis}\n</${tag}>`);
364
705
  continue;
365
706
  }