-
Notifications
You must be signed in to change notification settings - Fork 4
/
parser.js
505 lines (460 loc) · 13.1 KB
/
parser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/**
* @type {string}
*/
let document;
/**
* @type {number}
*/
let offset;
/**
* @type {ParsedBlock[]}
*/
let output;
/**
* @type {ParsedFrame[]}
*/
let stack;
/**
* @typedef {Object|null} Attributes
*/
/**
* @typedef {Object} ParsedBlock
* @property {string|null} blockName Block name.
* @property {Attributes} attrs Block attributes.
* @property {ParsedBlock[]} innerBlocks Inner blocks.
* @property {string} innerHTML Inner HTML.
* @property {Array<string|null>} innerContent Inner content.
*/
/**
* @typedef {Object} ParsedFrame
* @property {ParsedBlock} block Block.
* @property {number} tokenStart Token start.
* @property {number} tokenLength Token length.
* @property {number} prevOffset Previous offset.
* @property {number|null} leadingHtmlStart Leading HTML start.
*/
/**
* @typedef {'no-more-tokens'|'void-block'|'block-opener'|'block-closer'} TokenType
*/
/**
* @typedef {[TokenType, string, Attributes, number, number]} Token
*/
/**
* Matches block comment delimiters
*
* While most of this pattern is straightforward the attribute parsing
* incorporates a tricks to make sure we don't choke on specific input
*
* - since JavaScript has no possessive quantifier or atomic grouping
* we are emulating it with a trick
*
* we want a possessive quantifier or atomic group to prevent backtracking
* on the `}`s should we fail to match the remainder of the pattern
*
* we can emulate this with a positive lookahead and back reference
* (a++)*c === ((?=(a+))\1)*c
*
* let's examine an example:
* - /(a+)*c/.test('aaaaaaaaaaaaad') fails after over 49,000 steps
* - /(a++)*c/.test('aaaaaaaaaaaaad') fails after 85 steps
* - /(?>a+)*c/.test('aaaaaaaaaaaaad') fails after 126 steps
*
* this is because the possessive `++` and the atomic group `(?>)`
* tell the engine that all those `a`s belong together as a single group
* and so it won't split it up when stepping backwards to try and match
*
* if we use /((?=(a+))\1)*c/ then we get the same behavior as the atomic group
* or possessive and prevent the backtracking because the `a+` is matched but
* not captured. thus, we find the long string of `a`s and remember it, then
* reference it as a whole unit inside our pattern
*
* @see http://instanceof.me/post/52245507631/regex-emulate-atomic-grouping-with-lookahead
* @see http://blog.stevenlevithan.com/archives/mimic-atomic-groups
* @see https://javascript.info/regexp-infinite-backtracking-problem
*
* once browsers reliably support atomic grouping or possessive
* quantifiers natively we should remove this trick and simplify
*
* @type {RegExp}
*
* @since 3.8.0
* @since 4.6.1 added optimization to prevent backtracking on attribute parsing
*/
const tokenizer =
/<!--\s+(\/)?wp:([a-z][a-z0-9_-]*\/)?([a-z][a-z0-9_-]*)\s+({(?:(?=([^}]+|}+(?=})|(?!}\s+\/?-->)[^])*)\5|[^]*?)}\s+)?(\/)?-->/g;
/**
* Constructs a block object.
*
* @param {string|null} blockName
* @param {Attributes} attrs
* @param {ParsedBlock[]} innerBlocks
* @param {string} innerHTML
* @param {string[]} innerContent
* @return {ParsedBlock} The block object.
*/
function Block( blockName, attrs, innerBlocks, innerHTML, innerContent ) {
return {
blockName,
attrs,
innerBlocks,
innerHTML,
innerContent,
};
}
/**
* Constructs a freeform block object.
*
* @param {string} innerHTML
* @return {ParsedBlock} The freeform block object.
*/
function Freeform( innerHTML ) {
return Block( null, {}, [], innerHTML, [ innerHTML ] );
}
/**
* Constructs a frame object.
*
* @param {ParsedBlock} block
* @param {number} tokenStart
* @param {number} tokenLength
* @param {number} prevOffset
* @param {number|null} leadingHtmlStart
* @return {ParsedFrame} The frame object.
*/
function Frame( block, tokenStart, tokenLength, prevOffset, leadingHtmlStart ) {
return {
block,
tokenStart,
tokenLength,
prevOffset: prevOffset || tokenStart + tokenLength,
leadingHtmlStart,
};
}
/**
* Parser function, that converts input HTML into a block based structure.
*
* @param {string} doc The HTML document to parse.
*
* @example
* Input post:
* ```html
* <!-- wp:columns {"columns":3} -->
* <div class="wp-block-columns has-3-columns"><!-- wp:column -->
* <div class="wp-block-column"><!-- wp:paragraph -->
* <p>Left</p>
* <!-- /wp:paragraph --></div>
* <!-- /wp:column -->
*
* <!-- wp:column -->
* <div class="wp-block-column"><!-- wp:paragraph -->
* <p><strong>Middle</strong></p>
* <!-- /wp:paragraph --></div>
* <!-- /wp:column -->
*
* <!-- wp:column -->
* <div class="wp-block-column"></div>
* <!-- /wp:column --></div>
* <!-- /wp:columns -->
* ```
*
* Parsing code:
* ```js
* import { parse } from '@wordpress/block-serialization-default-parser';
*
* parse( post ) === [
* {
* blockName: "core/columns",
* attrs: {
* columns: 3
* },
* innerBlocks: [
* {
* blockName: "core/column",
* attrs: null,
* innerBlocks: [
* {
* blockName: "core/paragraph",
* attrs: null,
* innerBlocks: [],
* innerHTML: "\n<p>Left</p>\n"
* }
* ],
* innerHTML: '\n<div class="wp-block-column"></div>\n'
* },
* {
* blockName: "core/column",
* attrs: null,
* innerBlocks: [
* {
* blockName: "core/paragraph",
* attrs: null,
* innerBlocks: [],
* innerHTML: "\n<p><strong>Middle</strong></p>\n"
* }
* ],
* innerHTML: '\n<div class="wp-block-column"></div>\n'
* },
* {
* blockName: "core/column",
* attrs: null,
* innerBlocks: [],
* innerHTML: '\n<div class="wp-block-column"></div>\n'
* }
* ],
* innerHTML: '\n<div class="wp-block-columns has-3-columns">\n\n\n\n</div>\n'
* }
* ];
* ```
* @return {ParsedBlock[]} A block-based representation of the input HTML.
*/
export const parse = ( doc ) => {
document = doc;
offset = 0;
output = [];
stack = [];
tokenizer.lastIndex = 0;
do {
// twiddle our thumbs
} while ( proceed() );
return output;
};
/**
* Parses the next token in the input document.
*
* @return {boolean} Returns true when there is more tokens to parse.
*/
function proceed() {
const stackDepth = stack.length;
const next = nextToken();
const [ tokenType, blockName, attrs, startOffset, tokenLength ] = next;
// We may have some HTML soup before the next block.
const leadingHtmlStart = startOffset > offset ? offset : null;
switch ( tokenType ) {
case 'no-more-tokens':
// If not in a block then flush output.
if ( 0 === stackDepth ) {
addFreeform();
return false;
}
// Otherwise we have a problem
// This is an error
// we have options
// - treat it all as freeform text
// - assume an implicit closer (easiest when not nesting)
// For the easy case we'll assume an implicit closer.
if ( 1 === stackDepth ) {
addBlockFromStack();
return false;
}
// For the nested case where it's more difficult we'll
// have to assume that multiple closers are missing
// and so we'll collapse the whole stack piecewise.
while ( 0 < stack.length ) {
addBlockFromStack();
}
return false;
case 'void-block':
// easy case is if we stumbled upon a void block
// in the top-level of the document.
if ( 0 === stackDepth ) {
if ( null !== leadingHtmlStart ) {
output.push(
Freeform(
document.substr(
leadingHtmlStart,
startOffset - leadingHtmlStart
)
)
);
}
output.push( Block( blockName, attrs, [], '', [] ) );
offset = startOffset + tokenLength;
return true;
}
// Otherwise we found an inner block.
addInnerBlock(
Block( blockName, attrs, [], '', [] ),
startOffset,
tokenLength
);
offset = startOffset + tokenLength;
return true;
case 'block-opener':
// Track all newly-opened blocks on the stack.
stack.push(
Frame(
Block( blockName, attrs, [], '', [] ),
startOffset,
tokenLength,
startOffset + tokenLength,
leadingHtmlStart
)
);
offset = startOffset + tokenLength;
return true;
case 'block-closer':
// If we're missing an opener we're in trouble
// This is an error.
if ( 0 === stackDepth ) {
// We have options
// - assume an implicit opener
// - assume _this_ is the opener
// - give up and close out the document.
addFreeform();
return false;
}
// If we're not nesting then this is easy - close the block.
if ( 1 === stackDepth ) {
addBlockFromStack( startOffset );
offset = startOffset + tokenLength;
return true;
}
// Otherwise we're nested and we have to close out the current
// block and add it as a innerBlock to the parent.
const stackTop = /** @type {ParsedFrame} */ ( stack.pop() );
const html = document.substr(
stackTop.prevOffset,
startOffset - stackTop.prevOffset
);
stackTop.block.innerHTML += html;
stackTop.block.innerContent.push( html );
stackTop.prevOffset = startOffset + tokenLength;
addInnerBlock(
stackTop.block,
stackTop.tokenStart,
stackTop.tokenLength,
startOffset + tokenLength
);
offset = startOffset + tokenLength;
return true;
default:
// This is an error.
addFreeform();
return false;
}
}
/**
* Parse JSON if valid, otherwise return null
*
* Note that JSON coming from the block comment
* delimiters is constrained to be an object
* and cannot be things like `true` or `null`
*
* @param {string} input JSON input string to parse
* @return {Object|null} parsed JSON if valid
*/
function parseJSON( input ) {
try {
return JSON.parse( input );
} catch ( e ) {
return null;
}
}
/**
* Finds the next token in the document.
*
* @return {Token} The next matched token.
*/
function nextToken() {
// Aye the magic
// we're using a single RegExp to tokenize the block comment delimiters
// we're also using a trick here because the only difference between a
// block opener and a block closer is the leading `/` before `wp:` (and
// a closer has no attributes). we can trap them both and process the
// match back in JavaScript to see which one it was.
const matches = tokenizer.exec( document );
// We have no more tokens.
if ( null === matches ) {
return [ 'no-more-tokens', '', null, 0, 0 ];
}
const startedAt = matches.index;
const [
match,
closerMatch,
namespaceMatch,
nameMatch,
attrsMatch /* Internal/unused. */,
,
voidMatch,
] = matches;
const length = match.length;
const isCloser = !! closerMatch;
const isVoid = !! voidMatch;
const namespace = namespaceMatch || 'core/';
const name = namespace + nameMatch;
const hasAttrs = !! attrsMatch;
const attrs = hasAttrs ? parseJSON( attrsMatch ) : {};
// This state isn't allowed
// This is an error.
if ( isCloser && ( isVoid || hasAttrs ) ) {
// We can ignore them since they don't hurt anything
// we may warn against this at some point or reject it.
}
if ( isVoid ) {
return [ 'void-block', name, attrs, startedAt, length ];
}
if ( isCloser ) {
return [ 'block-closer', name, null, startedAt, length ];
}
return [ 'block-opener', name, attrs, startedAt, length ];
}
/**
* Adds a freeform block to the output.
*
* @param {number} [rawLength]
*/
function addFreeform( rawLength ) {
const length = rawLength ? rawLength : document.length - offset;
if ( 0 === length ) {
return;
}
output.push( Freeform( document.substr( offset, length ) ) );
}
/**
* Adds inner block to the parent block.
*
* @param {ParsedBlock} block
* @param {number} tokenStart
* @param {number} tokenLength
* @param {number} [lastOffset]
*/
function addInnerBlock( block, tokenStart, tokenLength, lastOffset ) {
const parent = stack[ stack.length - 1 ];
parent.block.innerBlocks.push( block );
const html = document.substr(
parent.prevOffset,
tokenStart - parent.prevOffset
);
if ( html ) {
parent.block.innerHTML += html;
parent.block.innerContent.push( html );
}
parent.block.innerContent.push( null );
parent.prevOffset = lastOffset ? lastOffset : tokenStart + tokenLength;
}
/**
* Adds block from the stack to the output.
*
* @param {number} [endOffset]
*/
function addBlockFromStack( endOffset ) {
const { block, leadingHtmlStart, prevOffset, tokenStart } =
/** @type {ParsedFrame} */ ( stack.pop() );
const html = endOffset
? document.substr( prevOffset, endOffset - prevOffset )
: document.substr( prevOffset );
if ( html ) {
block.innerHTML += html;
block.innerContent.push( html );
}
if ( null !== leadingHtmlStart ) {
output.push(
Freeform(
document.substr(
leadingHtmlStart,
tokenStart - leadingHtmlStart
)
)
);
}
output.push( block );
}