-
Notifications
You must be signed in to change notification settings - Fork 47
/
gatsby-node.ts
324 lines (298 loc) · 7.95 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
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
import { GatsbyNode, Node as _Node } from "gatsby";
import { createFilePath, FileSystemNode } from "gatsby-source-filesystem";
const path = require(`path`);
const asciidoc = require(`asciidoctor`)();
interface Node {
id: string;
fields: {
slug: string;
};
frontmatter: {
title: string;
date: string;
};
}
type Without<T, U> = Pick<T, Exclude<keyof T, keyof U>>;
type XOR<T, U> = T | U extends object
? (Without<T, U> & U) | (Without<U, T> & T)
: T | U;
interface QueryResult {
allFile: {
edges: {
node: XOR<{ childAsciidoc: Node }, { childMarkdownRemark: Node }>;
}[];
};
}
const isFileSystemNode = (node: _Node): node is FileSystemNode => {
return (node as FileSystemNode).absolutePath !== undefined;
};
export const onCreateNode: GatsbyNode["onCreateNode"] = async ({
node,
actions,
getNode,
createNodeId,
createContentDigest,
reporter,
}) => {
const { createNodeField, createParentChildLink, createNode } = actions;
if (isFileSystemNode(node) && ["adoc", "asciidoc"].includes(node.extension)) {
const asciidocOptions = {
safe: "unsafe",
to_file: false,
attributes: {
showtitle: false,
"site-baseurl": "/",
imagesdir: "/static/docs/",
upstream: true,
"skip-front-matter": true,
stem: "asciimath",
},
};
try {
var _title$getCombined, _title$getMain;
const doc = asciidoc.loadFile(node.absolutePath, asciidocOptions);
const html = doc.convert(asciidocOptions);
const title = doc.getDocumentTitle({
partition: true,
});
let sections = null;
if (doc.hasSections()) {
const flattenSections = (sections, parentId) => {
return sections.reduce((flattened, s) => {
const section = {
name: s.getTitle(),
id: s.getId(),
level: s.getLevel(),
index: s.getIndex(),
parentId: parentId,
};
const nestedSections = flattenSections(s.getSections(), section.id);
return flattened.concat(section, nestedSections);
}, []);
};
sections = flattenSections(doc.getSections(), null);
}
const extractPageAttributes = (allAttributes) =>
Object.entries(allAttributes).reduce((pageAttributes, [key, value]) => {
if (key.startsWith(`page-`)) {
pageAttributes[key.replace(/^page-/, ``)] = value;
}
return pageAttributes;
}, {});
const pageAttributes = extractPageAttributes(doc.getAttributes());
const asciiNode = {
id: createNodeId(`${node.id} >>> ASCIIDOC`),
parent: node.id,
internal: {
type: `Asciidoc`,
mediaType: `text/html`,
contentDigest: "",
},
children: [],
html,
document: {
title:
(_title$getCombined =
title === null || title === void 0
? void 0
: title.getCombined()) !== null && _title$getCombined !== void 0
? _title$getCombined
: ``,
subtitle:
title !== null && title !== void 0 && title.hasSubtitle()
? title.getSubtitle()
: ``,
main:
(_title$getMain =
title === null || title === void 0 ? void 0 : title.getMain()) !==
null && _title$getMain !== void 0
? _title$getMain
: ``,
},
sections,
pageAttributes,
};
asciiNode.internal.contentDigest = createContentDigest(asciiNode);
createNode(asciiNode);
createParentChildLink({
parent: node,
child: asciiNode,
});
} catch (err) {
reporter.panicOnBuild(`Error processing Asciidoc ${node.absolutePath ? `file ${node.absolutePath}` : `in node ${node.id}`
}:\n
${err}`);
}
}
if (
node.internal.type === "MarkdownRemark" ||
node.internal.type === "Asciidoc"
) {
const slug = createFilePath({ node, getNode, basePath: "src/content" });
const sourceInstanceName = getNode(node.parent!)!.sourceInstanceName;
if (sourceInstanceName === "pages") {
createNodeField({
node,
name: "slug",
value: slug
});
}
else {
createNodeField({
node,
name: "slug",
value: `/${sourceInstanceName}${slug}`,
});
}
}
};
export const createPages: GatsbyNode["createPages"] = async ({
graphql,
actions,
}) => {
const { createPage, createRedirect } = actions;
const docsResult = await graphql<QueryResult>(`
query docFiles {
allFile(filter: {sourceInstanceName: {eq: "docs"}}) {
edges {
node {
childAsciidoc {
document {
title
}
fields {
slug
}
id
}
childMarkdownRemark {
fields {
slug
}
id
frontmatter {
title
}
}
}
}
}
}
`);
const pagesResults = await graphql<QueryResult>(`
query pageFiles {
allFile(filter: {sourceInstanceName: {eq: "pages"}}) {
edges {
node {
childMarkdownRemark {
fields {
slug
}
id
frontmatter {
title
}
}
}
}
}
}
`);
const blogResult = await graphql<QueryResult>(`
query blogFiles {
allFile(filter: { sourceInstanceName: { eq: "blog" } }) {
edges {
node {
childMarkdownRemark {
excerpt
fields {
slug
}
frontmatter {
title
}
id
}
}
}
}
}
`);
if (docsResult.errors) {
throw docsResult.errors;
}
if (blogResult.errors) {
throw blogResult.errors;
}
if (pagesResults.errors) {
throw pagesResults.errors;
}
// create pages
const pages = pagesResults.data?.allFile.edges ?? [];
pages.forEach(({ node }) => {
if (node?.childMarkdownRemark?.fields?.slug) {
createPage({
path: node.childMarkdownRemark.fields.slug,
component: path.resolve("./src/templates/page.tsx"),
context: {
id: node.childMarkdownRemark.id,
},
});
}
});
// create docs pages
const docs = docsResult.data?.allFile.edges ?? [];
docs.forEach(({ node: _node }) => {
const node = _node.childAsciidoc ?? _node.childMarkdownRemark
if (node?.fields?.slug) {
createPage({
path: node.fields.slug,
component: path.resolve("./src/templates/docs-page.tsx"),
context: {
id: node.id,
},
});
}
});
// create blog post pages
const post = blogResult.data?.allFile.edges ?? [];
post.forEach(({ node }) => {
createPage({
path: node.childMarkdownRemark.fields.slug,
component: path.resolve("./src/templates/blog-post.tsx"),
context: {
id: node.childMarkdownRemark.id,
},
});
});
};
/**
* @type {import('gatsby').GatsbyNode['createSchemaCustomization']}
*/
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
// Explicitly define the siteMetadata {} object
// This way those will always be defined even if removed from gatsby-config.js
// Also explicitly define the Markdown frontmatter
// This way the "MarkdownRemark" queries will return `null` even when no
// blog posts are stored inside "content/blog" instead of returning an error
createTypes(`
type SiteSiteMetadata {
siteUrl: String
}
type MarkdownRemark implements Node {
frontmatter: Frontmatter
fields: Fields
}
type Frontmatter {
title: String
date: Date @dateformat
author: String
categories: String
preview: String
}
type Fields {
slug: String
}
`);
};