-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
extend-node-type.js
658 lines (620 loc) · 18.9 KB
/
extend-node-type.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
const {
GraphQLObjectType,
GraphQLList,
GraphQLString,
GraphQLInt,
GraphQLEnumType,
GraphQLJSON,
GraphQLBoolean,
} = require(`gatsby/graphql`)
const Remark = require(`remark`)
const select = require(`unist-util-select`)
const sanitizeHTML = require(`sanitize-html`)
const _ = require(`lodash`)
const visit = require(`unist-util-visit`)
const toHAST = require(`mdast-util-to-hast`)
const hastToHTML = require(`hast-util-to-html`)
const mdastToToc = require(`mdast-util-toc`)
const mdastToString = require(`mdast-util-to-string`)
const Promise = require(`bluebird`)
const unified = require(`unified`)
const parse = require(`remark-parse`)
const stringify = require(`remark-stringify`)
const english = require(`retext-english`)
const remark2retext = require(`remark-retext`)
const stripPosition = require(`unist-util-remove-position`)
const hastReparseRaw = require(`hast-util-raw`)
const prune = require(`underscore.string/prune`)
const {
getConcatenatedValue,
cloneTreeUntil,
findLastTextNode,
} = require(`./hast-processing`)
let fileNodes
let pluginsCacheStr = ``
let pathPrefixCacheStr = ``
const astCacheKey = node =>
`transformer-remark-markdown-ast-${
node.internal.contentDigest
}-${pluginsCacheStr}-${pathPrefixCacheStr}`
const htmlCacheKey = node =>
`transformer-remark-markdown-html-${
node.internal.contentDigest
}-${pluginsCacheStr}-${pathPrefixCacheStr}`
const htmlAstCacheKey = node =>
`transformer-remark-markdown-html-ast-${
node.internal.contentDigest
}-${pluginsCacheStr}-${pathPrefixCacheStr}`
const headingsCacheKey = node =>
`transformer-remark-markdown-headings-${
node.internal.contentDigest
}-${pluginsCacheStr}-${pathPrefixCacheStr}`
const tableOfContentsCacheKey = (node, appliedTocOptions) =>
`transformer-remark-markdown-toc-${
node.internal.contentDigest
}-${pluginsCacheStr}-${JSON.stringify(
appliedTocOptions
)}-${pathPrefixCacheStr}`
// ensure only one `/` in new url
const withPathPrefix = (url, pathPrefix) =>
(pathPrefix + url).replace(/\/\//, `/`)
// TODO: remove this check with next major release
const safeGetCache = ({ getCache, cache }) => id => {
if (!getCache) {
return cache
}
return getCache(id)
}
/**
* Map that keeps track of generation of AST to not generate it multiple
* times in parallel.
*
* @type {Map<string,Promise>}
*/
const ASTPromiseMap = new Map()
module.exports = (
{
type,
pathPrefix,
getNode,
getNodesByType,
cache,
getCache: possibleGetCache,
reporter,
...rest
},
pluginOptions
) => {
if (type.name !== `MarkdownRemark`) {
return {}
}
pluginsCacheStr = pluginOptions.plugins.map(p => p.name).join(``)
pathPrefixCacheStr = pathPrefix || ``
const getCache = safeGetCache({ cache, getCache: possibleGetCache })
return new Promise((resolve, reject) => {
// Setup Remark.
const {
blocks,
commonmark = true,
footnotes = true,
gfm = true,
pedantic = true,
tableOfContents = {
heading: null,
maxDepth: 6,
},
} = pluginOptions
const tocOptions = tableOfContents
const remarkOptions = {
commonmark,
footnotes,
gfm,
pedantic,
}
if (_.isArray(blocks)) {
remarkOptions.blocks = blocks
}
let remark = new Remark().data(`settings`, remarkOptions)
for (let plugin of pluginOptions.plugins) {
const requiredPlugin = require(plugin.resolve)
if (_.isFunction(requiredPlugin.setParserPlugins)) {
for (let parserPlugin of requiredPlugin.setParserPlugins(
plugin.pluginOptions
)) {
if (_.isArray(parserPlugin)) {
const [parser, options] = parserPlugin
remark = remark.use(parser, options)
} else {
remark = remark.use(parserPlugin)
}
}
}
}
async function getAST(markdownNode) {
const cacheKey = astCacheKey(markdownNode)
const cachedAST = await cache.get(cacheKey)
if (cachedAST) {
return cachedAST
} else if (ASTPromiseMap.has(cacheKey)) {
// We are already generating AST, so let's wait for it
return await ASTPromiseMap.get(cacheKey)
} else {
const ASTGenerationPromise = getMarkdownAST(markdownNode)
ASTGenerationPromise.then(markdownAST => {
ASTPromiseMap.delete(cacheKey)
return cache.set(cacheKey, markdownAST)
}).catch(err => {
ASTPromiseMap.delete(cacheKey)
return err
})
// Save new AST to cache and return
// We can now release promise, as we cached result
ASTPromiseMap.set(cacheKey, ASTGenerationPromise)
return ASTGenerationPromise
}
}
async function getMarkdownAST(markdownNode) {
if (process.env.NODE_ENV !== `production` || !fileNodes) {
fileNodes = getNodesByType(`File`)
}
// Use Bluebird's Promise function "each" to run remark plugins serially.
await Promise.each(pluginOptions.plugins, plugin => {
const requiredPlugin = require(plugin.resolve)
if (_.isFunction(requiredPlugin.mutateSource)) {
return requiredPlugin.mutateSource(
{
markdownNode,
files: fileNodes,
getNode,
reporter,
cache: getCache(plugin.name),
getCache,
...rest,
},
plugin.pluginOptions
)
} else {
return Promise.resolve()
}
})
const markdownAST = remark.parse(markdownNode.internal.content)
if (pathPrefix) {
// Ensure relative links include `pathPrefix`
visit(markdownAST, [`link`, `definition`], node => {
if (
node.url &&
node.url.startsWith(`/`) &&
!node.url.startsWith(`//`)
) {
node.url = withPathPrefix(node.url, pathPrefix)
}
})
}
// source => parse (can order parsing for dependencies) => typegen
//
// source plugins identify nodes, provide id, initial parse, know
// when nodes are created/removed/deleted
// get passed cached DataTree and return list of clean and dirty nodes.
// Also get passed `dirtyNodes` function which they can call with an array
// of node ids which will then get re-parsed and the inferred schema
// recreated (if inferring schema gets too expensive, can also
// cache the schema until a query fails at which point recreate the
// schema).
//
// parse plugins take data from source nodes and extend it, never mutate
// it. Freeze all nodes once done so typegen plugins can't change it
// this lets us save off the DataTree at that point as well as create
// indexes.
//
// typegen plugins identify further types of data that should be lazily
// computed due to their expense, or are hard to infer graphql type
// (markdown ast), or are need user input in order to derive e.g.
// markdown headers or date fields.
//
// wrap all resolve functions to (a) auto-memoize and (b) cache to disk any
// resolve function that takes longer than ~10ms (do research on this
// e.g. how long reading/writing to cache takes), and (c) track which
// queries are based on which source nodes. Also if connection of what
// which are always rerun if their underlying nodes change..
//
// every node type in DataTree gets a schema type automatically.
// typegen plugins just modify the auto-generated types to add derived fields
// as well as computationally expensive fields.
if (process.env.NODE_ENV !== `production` || !fileNodes) {
fileNodes = getNodesByType(`File`)
}
// Use Bluebird's Promise function "each" to run remark plugins serially.
await Promise.each(pluginOptions.plugins, plugin => {
const requiredPlugin = require(plugin.resolve)
if (_.isFunction(requiredPlugin)) {
return requiredPlugin(
{
markdownAST,
markdownNode,
getNode,
files: fileNodes,
pathPrefix,
reporter,
cache: getCache(plugin.name),
getCache,
...rest,
},
plugin.pluginOptions
)
} else {
return Promise.resolve()
}
})
return markdownAST
}
async function getHeadings(markdownNode) {
const cachedHeadings = await cache.get(headingsCacheKey(markdownNode))
if (cachedHeadings) {
return cachedHeadings
} else {
const ast = await getAST(markdownNode)
const headings = select(ast, `heading`).map(heading => {
return {
value: mdastToString(heading),
depth: heading.depth,
}
})
cache.set(headingsCacheKey(markdownNode), headings)
return headings
}
}
async function getTableOfContents(markdownNode, gqlTocOptions) {
// fetch defaults
let appliedTocOptions = { ...tocOptions, ...gqlTocOptions }
// get cached toc
const cachedToc = await cache.get(
tableOfContentsCacheKey(markdownNode, appliedTocOptions)
)
if (cachedToc) {
return cachedToc
} else {
const ast = await getAST(markdownNode)
const tocAst = mdastToToc(ast, appliedTocOptions)
let toc
if (tocAst.map) {
const addSlugToUrl = function(node) {
if (node.url) {
if (
_.get(markdownNode, appliedTocOptions.pathToSlugField) ===
undefined
) {
console.warn(
`Skipping TableOfContents. Field '${
appliedTocOptions.pathToSlugField
}' missing from markdown node`
)
return null
}
node.url = [
pathPrefix,
_.get(markdownNode, appliedTocOptions.pathToSlugField),
node.url,
]
.join(`/`)
.replace(/\/\//g, `/`)
}
if (node.children) {
node.children = node.children.map(node => addSlugToUrl(node))
}
return node
}
tocAst.map = addSlugToUrl(tocAst.map)
toc = hastToHTML(toHAST(tocAst.map))
} else {
toc = ``
}
cache.set(tableOfContentsCacheKey(markdownNode, appliedTocOptions), toc)
return toc
}
}
async function getHTMLAst(markdownNode) {
const cachedAst = await cache.get(htmlAstCacheKey(markdownNode))
if (cachedAst) {
return cachedAst
} else {
const ast = await getAST(markdownNode)
const htmlAst = toHAST(ast, { allowDangerousHTML: true })
// Save new HTML AST to cache and return
cache.set(htmlAstCacheKey(markdownNode), htmlAst)
return htmlAst
}
}
async function getHTML(markdownNode) {
const cachedHTML = await cache.get(htmlCacheKey(markdownNode))
if (cachedHTML) {
return cachedHTML
} else {
const ast = await getHTMLAst(markdownNode)
// Save new HTML to cache and return
const html = hastToHTML(ast, {
allowDangerousHTML: true,
})
// Save new HTML to cache and return
cache.set(htmlCacheKey(markdownNode), html)
return html
}
}
async function getExcerptAst(
markdownNode,
{ pruneLength, truncate, excerptSeparator }
) {
const fullAST = await getHTMLAst(markdownNode)
if (excerptSeparator) {
return cloneTreeUntil(
fullAST,
({ nextNode }) =>
nextNode.type === `raw` && nextNode.value === excerptSeparator
)
}
if (!fullAST.children.length) {
return fullAST
}
const excerptAST = cloneTreeUntil(fullAST, ({ root }) => {
const totalExcerptSoFar = getConcatenatedValue(root)
return totalExcerptSoFar && totalExcerptSoFar.length > pruneLength
})
const unprunedExcerpt = getConcatenatedValue(excerptAST)
if (
!unprunedExcerpt ||
(pruneLength && unprunedExcerpt.length < pruneLength)
) {
return excerptAST
}
const lastTextNode = findLastTextNode(excerptAST)
const amountToPruneLastNode =
pruneLength - (unprunedExcerpt.length - lastTextNode.value.length)
if (!truncate) {
lastTextNode.value = prune(
lastTextNode.value,
amountToPruneLastNode,
`…`
)
} else {
lastTextNode.value = _.truncate(lastTextNode.value, {
length: pruneLength,
omission: `…`,
})
}
return excerptAST
}
async function getExcerpt(
markdownNode,
{ format, pruneLength, truncate, excerptSeparator }
) {
if (format === `html`) {
const excerptAST = await getExcerptAst(markdownNode, {
pruneLength,
truncate,
excerptSeparator,
})
const html = hastToHTML(excerptAST, {
allowDangerousHTML: true,
})
return html
}
if (markdownNode.excerpt) {
return markdownNode.excerpt
}
const text = await getAST(markdownNode).then(ast => {
let excerptNodes = []
visit(ast, node => {
if (node.type === `text` || node.type === `inlineCode`) {
excerptNodes.push(node.value)
}
if (node.type === `image`) {
excerptNodes.push(node.alt)
}
return
})
if (!truncate) {
return prune(excerptNodes.join(``), pruneLength, `…`)
}
return _.truncate(excerptNodes.join(``), {
length: pruneLength,
omission: `…`,
})
})
return text
}
const HeadingType = new GraphQLObjectType({
name: `MarkdownHeading`,
fields: {
value: {
type: GraphQLString,
resolve(heading) {
return heading.value
},
},
depth: {
type: GraphQLInt,
resolve(heading) {
return heading.depth
},
},
},
})
const HeadingLevels = new GraphQLEnumType({
name: `HeadingLevels`,
values: {
h1: { value: 1 },
h2: { value: 2 },
h3: { value: 3 },
h4: { value: 4 },
h5: { value: 5 },
h6: { value: 6 },
},
})
const ExcerptFormats = new GraphQLEnumType({
name: `ExcerptFormats`,
values: {
PLAIN: { value: `plain` },
HTML: { value: `html` },
},
})
const WordCountType = new GraphQLObjectType({
name: `wordCount`,
fields: {
paragraphs: {
type: GraphQLInt,
},
sentences: {
type: GraphQLInt,
},
words: {
type: GraphQLInt,
},
},
})
return resolve({
html: {
type: GraphQLString,
resolve(markdownNode) {
return getHTML(markdownNode)
},
},
htmlAst: {
type: GraphQLJSON,
resolve(markdownNode) {
return getHTMLAst(markdownNode).then(ast => {
const strippedAst = stripPosition(_.clone(ast), true)
return hastReparseRaw(strippedAst)
})
},
},
excerpt: {
type: GraphQLString,
args: {
pruneLength: {
type: GraphQLInt,
defaultValue: 140,
},
truncate: {
type: GraphQLBoolean,
defaultValue: false,
},
format: {
type: ExcerptFormats,
defaultValue: `plain`,
},
},
resolve(markdownNode, { format, pruneLength, truncate }) {
return getExcerpt(markdownNode, {
format,
pruneLength,
truncate,
excerptSeparator: pluginOptions.excerpt_separator,
})
},
},
excerptAst: {
type: GraphQLJSON,
args: {
pruneLength: {
type: GraphQLInt,
defaultValue: 140,
},
truncate: {
type: GraphQLBoolean,
defaultValue: false,
},
},
resolve(markdownNode, { pruneLength, truncate }) {
return getExcerptAst(markdownNode, {
pruneLength,
truncate,
excerptSeparator: pluginOptions.excerpt_separator,
}).then(ast => {
const strippedAst = stripPosition(_.clone(ast), true)
return hastReparseRaw(strippedAst)
})
},
},
headings: {
type: new GraphQLList(HeadingType),
args: {
depth: {
type: HeadingLevels,
},
},
resolve(markdownNode, { depth }) {
return getHeadings(markdownNode).then(headings => {
if (typeof depth === `number`) {
headings = headings.filter(heading => heading.depth === depth)
}
return headings
})
},
},
timeToRead: {
type: GraphQLInt,
resolve(markdownNode) {
return getHTML(markdownNode).then(html => {
let timeToRead = 0
const pureText = sanitizeHTML(html, { allowTags: [] })
const avgWPM = 265
const wordCount = _.words(pureText).length
timeToRead = Math.round(wordCount / avgWPM)
if (timeToRead === 0) {
timeToRead = 1
}
return timeToRead
})
},
},
tableOfContents: {
type: GraphQLString,
args: {
pathToSlugField: {
type: GraphQLString,
defaultValue: `fields.slug`,
},
maxDepth: {
type: GraphQLInt,
},
heading: {
type: GraphQLString,
},
},
resolve(markdownNode, args) {
return getTableOfContents(markdownNode, args)
},
},
// TODO add support for non-latin languages https://github.com/wooorm/remark/issues/251#issuecomment-296731071
wordCount: {
type: WordCountType,
resolve(markdownNode) {
let counts = {}
unified()
.use(parse)
.use(
remark2retext,
unified()
.use(english)
.use(count)
)
.use(stringify)
.processSync(markdownNode.internal.content)
return {
paragraphs: counts.ParagraphNode,
sentences: counts.SentenceNode,
words: counts.WordNode,
}
function count() {
return counter
function counter(tree) {
visit(tree, visitor)
function visitor(node) {
counts[node.type] = (counts[node.type] || 0) + 1
}
}
}
},
},
})
})
}