This repository has been archived by the owner on Jul 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 128
/
gatsby-node.ts
295 lines (261 loc) · 7.67 KB
/
gatsby-node.ts
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
/* eslint-disable simple-import-sort/imports */
// eslint complains about path not being before 'gatsby' but it is
import { execSync } from 'child_process'
import path from 'path'
import type { GatsbyNode } from 'gatsby'
import readingTime from 'reading-time'
import slug from 'slug'
import { MdxNode } from './src/types/mdxNode'
import { SiteMetadata } from './src/types/siteMetadata'
import getFinalDestination from './getFinalDestination'
import redirectRules from './redirectRules'
import { getFlaggedPagesConfig } from './src/utils/flaggedPages/ld-server'
import { compileMDXWithCustomOptions } from 'gatsby-plugin-mdx'
import remarkCreateCustomToc from './plugins/custom-toc'
const isDev = process.env.GATSBY_ACTIVE_ENV === 'development'
// This generates URL-safe slugs.
slug.defaults.mode = 'rfc3986'
const MdxPage = path.resolve('./src/layouts/mdxPage.tsx')
const getLastModifiedFromGitLog = (absolutePath: string) => {
return execSync(`git log -1 --pretty=format:%aI ${absolutePath}`).toString()
}
export const onCreateNode: GatsbyNode<MdxNode>['onCreateNode'] = async ({ node, actions }) => {
const { createNodeField } = actions
const {
internal: { type, contentFilePath },
} = node
if (type === 'Mdx' && contentFilePath) {
const repoPrefix = 'ld-docs-private/src/'
const fileRelativePath = contentFilePath.substring(contentFilePath.indexOf(repoPrefix) + repoPrefix.length)
let lastModifiedTime
if (isDev) {
lastModifiedTime = getLastModifiedFromGitLog(contentFilePath)
} else {
const gitCommits = JSON.parse(
execSync(`
gh api -XGET \\
-H "Accept: application/vnd.github.v3+json" \\
/repos/launchdarkly/ld-docs-private/commits \\
-F path=src/${fileRelativePath}`).toString(),
)
// the first commit is most recent one. Fallback to git log.
lastModifiedTime = gitCommits[0]?.commit?.author?.date ?? getLastModifiedFromGitLog(contentFilePath)
// if lastModified is still empty then use today's date
if (!lastModifiedTime || lastModifiedTime === '') {
lastModifiedTime = new Date().toISOString()
}
}
createNodeField({
name: 'lastModifiedTime',
node,
value: lastModifiedTime,
})
createNodeField({
name: 'isLandingPage',
node,
value: !!node.frontmatter.isLandingPage,
})
createNodeField({
name: 'fileAbsolutePath',
node,
value: contentFilePath,
})
createNodeField({
node,
name: 'timeToRead',
value: Math.ceil(readingTime(node.body, { wordsPerMinute: 240 }).minutes),
})
}
}
type PageQuery = {
allMdx: {
nodes: MdxNode[]
}
}
type SiteQuery = {
site: {
siteMetadata: SiteMetadata
}
}
export const createPages: GatsbyNode['createPages'] = async ({ graphql, actions, reporter }) => {
const { createRedirect, createPage } = actions
const redirectMap = redirectRules.reduce((map, r) => ({ ...map, [r.fromPath]: r.toPath }), {})
redirectRules.forEach(({ fromPath }) => {
console.log(`Attempting to create redirect from: ${fromPath}`)
createRedirect({
fromPath,
toPath: getFinalDestination(redirectMap, fromPath),
isPermanent: true,
redirectInBrowser: true,
})
if (fromPath.startsWith('/docs')) {
createRedirect({
fromPath: '/v2.0' + fromPath,
toPath: getFinalDestination(redirectMap, fromPath),
isPermanent: true,
redirectInBrowser: true,
})
}
})
const { isPathDisabled } = await getFlaggedPagesConfig()
const siteResult = await graphql<SiteQuery>(`
query {
site {
siteMetadata {
title
siteUrl
}
}
}
`)
const { siteMetadata } = siteResult.data.site
// https://github.com/algolia/gatsby-plugin-algolia#partial-updates
// internal.contentDigest is required
// Querying for pageData during createPages because
// mdx seems to have an issue with running out of memory
// when using page queries
const result = await graphql<PageQuery>(`
{
allMdx(filter: { frontmatter: { published: { eq: true } } }) {
nodes {
id
customToc
frontmatter {
path
isInternal
description
title
site
siteAlertTitle
}
internal {
contentFilePath
contentDigest
}
fileAbsolutePath
timeToRead
lastModifiedTime
isLandingPage
modifiedDate
}
}
}
`)
if (result.errors) {
reporter.panicOnBuild('🚨 ERROR: Loading "createPages" query')
}
const mdxFiles = result.data.allMdx.nodes
for (const node of mdxFiles) {
const {
id,
frontmatter,
internal,
customToc,
fileAbsolutePath,
timeToRead,
lastModifiedTime,
isLandingPage,
modifiedDate,
} = node
if (isPathDisabled(frontmatter.path)) {
console.info(`🚨 Skipping ${frontmatter.path} because it is disabled`)
continue
}
createPage({
path: frontmatter.path,
// have to use the param here with page component to properly generate the html head
component: frontmatter.isInternal
? internal.contentFilePath
: `${MdxPage}?__contentFilePath=${internal.contentFilePath}`,
context: {
id,
// using customToc instead of toc from tableOfContents so it doesnt skip nested headings in the
// case of flagged headings (headings within <Feature></Feature>)
toc: customToc,
fileAbsolutePath,
lastModifiedTime,
modifiedDate,
isLandingPage,
timeToRead,
siteMetadata,
},
})
}
}
export const createSchemaCustomization: GatsbyNode['createSchemaCustomization'] = async ({
actions,
schema,
getNode,
getNodesByType,
pathPrefix,
reporter,
cache,
store,
}) => {
const { createTypes } = actions
const customTocResolver = schema.buildObjectType({
name: 'Mdx',
fields: {
customToc: {
type: 'JSON',
async resolve(mdxNode) {
const fileNode = getNode(mdxNode.parent)
if (!fileNode) {
return null
}
const result = await compileMDXWithCustomOptions(
{
source: mdxNode.body,
absolutePath: fileNode.absolutePath as string,
},
{
pluginOptions: { plugins: [] },
customOptions: {
mdxOptions: {
remarkPlugins: [remarkCreateCustomToc],
},
},
getNode,
getNodesByType,
pathPrefix,
reporter,
cache,
store,
},
)
if (!result) {
return null
}
return result.metadata.customToc
},
},
},
})
const typeDefs = `
type NavigationDataJson implements Node {
flagKey: String
}
type NavigationDataJsonItems {
flagKey: String
}
type NavigationDataJsonItemsItems {
flagKey: String
}
type NavigationDataJsonItemsItemsItems {
flagKey: String
}
type Mdx implements Node {
fileAbsolutePath: String @proxy(from: "fields.fileAbsolutePath")
timeToRead: Int @proxy(from: "fields.timeToRead")
isLandingPage: Boolean @proxy(from: "fields.isLandingPage")
lastModifiedTime: Date @proxy(from: "fields.lastModifiedTime")
modifiedDate: Date @proxy(from: "fields.lastModifiedTime") @dateformat(formatString: "MMM DD, YYYY")
}
type CustomToc {
value: String
hash: String
depth: Int
}
`
createTypes([typeDefs, customTocResolver])
}