forked from npm/documentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.mjs
295 lines (269 loc) · 7.61 KB
/
gatsby-node.mjs
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
import {join, relative} from 'path'
import {Octokit as CoreOctokit} from '@octokit/rest'
import {throttling} from '@octokit/plugin-throttling'
import {retry} from '@octokit/plugin-retry'
import webpackConfig from './webpack.config.js'
const CI = !!process.env.CI
const CWD = process.cwd()
const SRC = join(CWD, 'src')
const REPO_URL = 'https://github.com/npm/documentation'
const NWO = new URL(REPO_URL).pathname.slice(1)
const REPO_BRANCH = 'main'
const TEST_CONTRIBUTORS = [
{
author: {login: 'mona'},
commit: {author: {date: new Date('2023-03-21').toJSON()}},
html_url: REPO_URL,
},
]
const createOctokit = ({reporter}) => {
const Octokit = CoreOctokit.plugin(throttling).plugin(retry)
return new Octokit({
log: {
debug: () => {},
info: reporter.info,
warn: reporter.warn,
error: reporter.error,
},
auth: process.env.GITHUB_TOKEN,
throttle: {
onRateLimit: (retryAfter, options, {log}, retryCount) => {
log.warn(`Request quota exhausted for request ${options.method} ${options.url}`)
if (retryCount < 2) {
log.info(`Retrying after ${retryAfter} seconds`)
return true
}
},
onSecondaryRateLimit: (_, options, {log}) => {
log.warn(`SecondaryRateLimit detected for request ${options.method} ${options.url}`)
},
},
})
}
export const onCreateNode = ({node, actions, getNode}) => {
if (node.internal.type === 'Mdx') {
const {name, relativeDirectory: dir} = getNode(node.parent)
// These paths are unchanged:
// - directory indexes
// - all cli paths
// - all policies paths
if (name === 'index' || dir.startsWith('cli/') || dir.startsWith('policies')) {
return
}
// otherwise, omit the directory path and use the filename as the slug
actions.createNodeField({
name: 'slug',
node,
value: name,
})
}
}
export const onCreateWebpackConfig = ({stage, actions}) => {
actions.setWebpackConfig({
...webpackConfig,
})
if (stage === `build-javascript`) {
actions.setWebpackConfig({
devtool: false,
})
}
}
export const createSchemaCustomization = ({actions: {createTypes}}) => {
createTypes(`
type Mdx implements Node {
frontmatter: MdxFrontmatter
fields: MdxFields
}
type MdxFrontmatter {
edit_on_github: Boolean,
github_branch: String,
github_path: String,
github_repo: String,
redirect_from: [String],
slug: String,
title: String
}
type MdxFields {
slug: String
}
`)
}
export const createPages = async ({graphql, actions, reporter}) => {
const response = await graphql(`
{
allMdx {
nodes {
id
internal {
contentFilePath
}
fields {
slug
}
frontmatter {
edit_on_github
github_branch
github_path
github_repo
redirect_from
slug
title
}
tableOfContents
parent {
... on File {
relativeDirectory
name
}
}
}
}
}
`)
if (response.errors) {
reporter.panic('Error getting allMdx', response.errors)
return
}
const octokit = createOctokit({reporter})
// Turn every MDX file into a page.
return Promise.all(
response.data.allMdx.nodes.map(async node => {
try {
node.fields ||= {}
node.frontmatter ||= {}
node.frontmatter.redirect_from ||= []
node.tableOfContents ||= {}
node.tableOfContents.items ||= []
return await createPage(node, {actions, reporter, octokit})
} catch (err) {
reporter.panic(`Error creating page: ${JSON.stringify(node, null, 2)}`, err)
}
}),
)
}
const createPage = async (
{
id,
internal: {contentFilePath},
fields: {slug},
frontmatter = {},
tableOfContents = {},
parent: {relativeDirectory, name: parentName},
},
{actions, reporter, octokit},
) => {
const path = relative(CWD, contentFilePath)
// sites can programmatically override slug, that takes priority
// then a slug specified in frontmatter
// finally, we'll just use the path on disk
const pageSlug =
slug ?? frontmatter.slug ?? join(relativeDirectory, parentName === 'index' ? '/' : parentName).replace(/\\/g, '/')
const context = {
mdxId: id,
tableOfContents: getTableOfConents(tableOfContents),
}
// edit_on_github: false in frontmatter will not include editUrl and contributors
// on the page. this is used for policy pages as well as some index pages that don't
// have any editable content
if (frontmatter.edit_on_github !== false) {
context.editUrl = getRepo(path, frontmatter).replace(`https://github.com/{nwo}/edit/{branch}/{path}`)
Object.assign(context, await fetchContributors(path, frontmatter, {reporter, octokit}))
}
actions.createPage({
path: pageSlug,
component: `${join(SRC, 'head.js')}?__contentFilePath=${contentFilePath}`,
context,
})
for (const from of frontmatter.redirect_from) {
actions.createRedirect({
fromPath: from,
toPath: `/${pageSlug}`,
isPermanent: true,
redirectInBrowser: true,
})
if (pageSlug.startsWith('cli/') && !from.endsWith('index')) {
actions.createRedirect({
fromPath: `${from}.html`,
toPath: `/${pageSlug}`,
isPermanent: true,
redirectInBrowser: true,
})
}
}
}
const getTableOfConents = ({items}) => {
// Fix some old CLI pages which have mismatched headings at the top level.
// All top level headings should be the same level.
const tableOfContents = items.reduce((acc, item) => {
if (!item.url && Array.isArray(item.items)) {
acc.push(...item.items)
} else {
acc.push(item)
}
return acc
}, [])
if (tableOfContents.length) {
return tableOfContents
}
}
const getRepo = (path, fm) => {
const result = {
nwo: NWO,
branch: REPO_BRANCH,
...(fm.github_repo ? {nwo: fm.github_repo} : {}),
...(fm.github_branch ? {branch: fm.github_branch} : {}),
path: fm.github_path || path,
}
const [owner, repo] = result.nwo.split('/')
result.owner = owner
result.repo = repo
result.replace = str => str.replace(/\{([a-z]+)\}/g, (_, name) => result[name])
return result
}
let warnOnNoContributors = true
const fetchContributors = async (path, fm, {reporter, octokit}) => {
const noAuth = (await octokit.auth()).type === 'unauthenticated'
if (noAuth) {
const msg = `Cannot fetch contributors without GitHub authentication.`
if (CI) {
reporter.panic(msg)
return
}
if (warnOnNoContributors) {
warnOnNoContributors = false
reporter.warn(`${msg} Pages will be include test contributor data.`)
}
}
try {
const repo = getRepo(path, fm)
const resp = noAuth
? {data: TEST_CONTRIBUTORS}
: await octokit.rest.repos.listCommits({
repo: repo.repo,
owner: repo.owner,
path: repo.path,
sha: repo.branch,
per_page: 100,
})
const contributors = new Set()
let latestCommit = null
for (const item of resp.data) {
if (item.author?.login) {
contributors.add(item.author.login)
if (!latestCommit) {
latestCommit = {
login: item.author.login,
date: item.commit.author.date,
url: item.html_url,
}
}
}
}
return {
contributors: [...contributors],
latestCommit,
}
} catch (err) {
reporter[CI ? 'panic' : 'error'](`Error fetching contributors for ${path}`, err)
}
}