forked from EnterpriseDB/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gatsby-node.js
750 lines (680 loc) · 20.9 KB
/
gatsby-node.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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
// this patch is required to consistently load all the doc files
const realFs = require("fs");
const path = require("path");
const gracefulFs = require("graceful-fs");
gracefulFs.gracefulify(realFs);
const { createFilePath } = require(`gatsby-source-filesystem`);
const { exec, execSync } = require("child_process");
const {
replacePathVersion,
filePathToDocType,
removeTrailingSlash,
isPathAnIndexPage,
pathToDepth,
mdxNodesToTree,
computeFrontmatterForTreeNode,
buildProductVersions,
reportMissingIndex,
treeToNavigation,
treeNodeToNavNode,
findPrevNextNavNodes,
preprocessPathsAndRedirects,
configureRedirects,
reportRedirectCollisions,
configureLegacyRedirects,
readFile,
writeFile,
makeFileNodePublic,
} = require("./src/constants/gatsby-utils.js");
const gitData = (() => {
// if this build was triggered by a GH action in response to a PR,
// use the head ref (the branch that someone is requesting be merged)
let branch = process.env.GITHUB_HEAD_REF;
// if this process was otherwise triggered by a GH action, use the current branch name
if (!branch) branch = process.env.GITHUB_REF;
// assuming this is triggered by a GH action, this will be the commit that triggered the workflow
let sha = process.env.GITHUB_SHA;
// non-GH Action build? Try actually running Git for the name & sha...
if (!branch) {
try {
branch = execSync("git rev-parse --abbrev-ref HEAD").toString();
sha = execSync("git rev-parse HEAD").toString();
} catch {}
}
if (!branch)
branch = process.env.APP_ENV === "production" ? "main" : "develop";
if (!sha) sha = "";
branch = branch
.trim()
.replace(/^refs\/heads\//, "")
.replace(/^refs\/tags\//, "");
sha = sha.trim();
return { branch, sha, docsRepoUrl: "https://github.com/EnterpriseDB/docs" };
})();
exports.onCreateNode = async ({
node,
getNode,
createNodeId,
actions,
loadNodeContent,
}) => {
const { createNodeField } = actions;
if (node.internal.type === "File") {
if (node.internal.mediaType === "application/pdf") {
await makeFileNodePublic(node, createNodeId, actions, {
basePath: "pdfs",
});
}
if (node.extension === "yaml") {
await makeFileNodePublic(node, createNodeId, actions, {
mimeType: "text/plain; charset=utf-8",
});
}
}
if (node.internal.type !== "Mdx") return;
const fileNode = getNode(node.parent);
const nodeFields = {
docType: filePathToDocType(node.fileAbsolutePath),
mtime: fileNode.mtime,
};
let relativeFilePath = createFilePath({ node, getNode });
if (nodeFields.docType === "doc") {
relativeFilePath = `/${fileNode.sourceInstanceName}${relativeFilePath}`;
}
Object.assign(nodeFields, {
path: relativeFilePath,
depth: pathToDepth(relativeFilePath),
});
if (nodeFields.docType === "doc") {
Object.assign(nodeFields, {
product: relativeFilePath.split("/")[1],
version: relativeFilePath.split("/")[2],
topic: "null",
});
} else if (nodeFields.docType === "advocacy") {
Object.assign(nodeFields, {
product: "null",
version: "0",
topic: relativeFilePath.split("/")[2],
});
}
for (const [name, value] of Object.entries(nodeFields)) {
createNodeField({ node, name: name, value: value });
}
};
exports.createPages = async ({ actions, graphql, reporter }) => {
const toolPath = path.join(
__dirname,
"tools",
"automation",
"generators",
"refbuilder",
);
command = `cd ${toolPath};npm ci;node ${path.join(
toolPath,
"refbuilder.js",
)} --source ${path.join(
__dirname,
"product_docs",
"docs",
"pgd",
"5",
"reference",
)}`;
execSync(command);
const result = await graphql(`
query {
allMdx {
nodes {
id
frontmatter {
title
navTitle
description
redirects
iconName
originalFilePath
productStub
indexCards
originalFilePath
editTarget
navigation
legacyRedirects
legacyRedirectsGenerated
navigation
showInteractiveBadge
hideToC
deepToC
hideKBLink
katacodaPages {
scenario
account
}
katacodaPanel {
scenario
account
initializeCommand
codelanguages
}
hideVersion
displayBanner
directoryDefaults {
description
prevNext
iconName
editTarget
product
platform
indexCards
showInteractiveBadge
hideKBLink
hideVersion
displayBanner
}
}
fields {
docType
path
depth
product
version
topic
}
fileAbsolutePath
}
}
allPublicFile {
nodes {
urlPath
product
version
parent {
... on File {
relativePath
}
}
}
}
}
`);
if (result.errors) {
reporter.panic("createPages graphql query has errors!", result.errors);
}
// this is critical to avoiding excessive Netlify deploy times: it ensures the pages are ordered consistently from build to build
result.data.allMdx.nodes = result.data.allMdx.nodes.sort((a, b) =>
a.fields.path.localeCompare(b.fields.path),
);
const { nodes } = result.data.allMdx;
const productVersions = buildProductVersions(nodes);
const validPaths = preprocessPathsAndRedirects(nodes, productVersions);
processFileNodes(result.data.allPublicFile.nodes, productVersions, actions);
// it should be possible to remove these in the future,
// they are only used for navLinks generation
const learn = nodes.filter((file) => file.fields.docType === "advocacy");
// perform depth first preorder traversal
const treeRoot = mdxNodesToTree(nodes);
const navStack = [treeRoot];
let curr = null;
while (navStack.length > 0) {
curr = navStack.pop();
curr.children.forEach((child) => navStack.push(child));
// build ordered navigation for immediate children
// treeToNavigation will use this data
const addedChildPaths = {};
curr.navigationNodes = [];
(curr.mdxNode?.frontmatter?.navigation || []).forEach((navEntry) => {
if (navEntry.startsWith("#")) {
curr.navigationNodes.push({
path: null,
title: navEntry.replace("#", "").trim(),
});
return;
}
const navChild = curr.children.find((child) => {
if (addedChildPaths[child.path]) return false;
const navName = child.path.split("/").slice(-2)[0];
return navName.toLowerCase() === navEntry.toLowerCase();
});
if (!navChild?.mdxNode) return;
addedChildPaths[navChild.path] = true;
curr.navigationNodes.push(treeNodeToNavNode(navChild));
});
curr.children
.filter((child) => !addedChildPaths[child.path])
.map((child) => treeNodeToNavNode(child))
.sort((a, b) => a.path.localeCompare(b.path))
.forEach((child) => curr.navigationNodes.push(child));
// exit here if we're not dealing with an actual page
if (!curr.mdxNode) {
reportMissingIndex(reporter, curr);
continue;
}
const node = curr.mdxNode;
// set computed frontmatter
node.frontmatter = computeFrontmatterForTreeNode(curr);
// build navigation tree
const navigationDepth = 1;
let navRoot = curr;
while (navRoot.depth > navigationDepth && navRoot?.parent?.mdxNode)
navRoot = navRoot.parent;
const navTree = treeToNavigation(navRoot, node);
// determine next and previous nodes
const prevNext = findPrevNextNavNodes(navTree, curr);
const pathVersions = configureRedirects(
productVersions,
node,
validPaths,
actions,
);
const { docType } = node.fields;
if (docType === "doc") {
createDoc(
navTree,
prevNext,
node,
productVersions,
pathVersions,
actions,
);
} else if (docType === "advocacy") {
createAdvocacy(navTree, prevNext, node, productVersions, learn, actions);
}
}
reportRedirectCollisions(validPaths, reporter);
};
const createDoc = (
navTree,
prevNext,
doc,
productVersions,
pathVersions,
actions,
) => {
const isLatest =
productVersions[doc.fields.product][0] === doc.fields.version;
// configure legacy redirects
if (!doc.frontmatter.productStub) {
configureLegacyRedirects({
toPath: doc.fields.path,
toLatestPath: replacePathVersion(doc.fields.path),
redirects: (doc.frontmatter.legacyRedirects || []).concat(
doc.frontmatter.legacyRedirectsGenerated || [],
),
actions,
});
}
const template = doc.frontmatter.productStub ? "doc-stub.js" : "doc.js";
const path = isLatest ? replacePathVersion(doc.fields.path) : doc.fields.path;
actions.createPage({
path: path,
component: require.resolve(`./src/templates/${template}`),
context: {
frontmatter: doc.frontmatter,
pagePath: path,
navTree,
prevNext,
productVersions,
versions: productVersions[doc.fields.product],
nodeId: doc.id,
pathVersions,
},
});
(doc.frontmatter.katacodaPages || []).forEach((katacodaPage) => {
if (!katacodaPage.scenario || !katacodaPage.account) {
throw new Error(
`katacoda scenario or account missing for ${doc.fields.path}`,
);
}
const path = `${doc.fields.path}${katacodaPage.scenario}`;
actions.createPage({
path: path,
component: require.resolve("./src/templates/katacoda-page.js"),
context: {
...katacodaPage,
pagePath: path,
learn: {
title: doc.frontmatter.title,
description: doc.frontmatter.description,
},
},
});
});
};
const createAdvocacy = (
navTree,
prevNext,
doc,
productVersions,
learn,
actions,
) => {
// configure legacy redirects
configureLegacyRedirects({
toPath: doc.fields.path,
toLatestPath: doc.fields.path,
redirects: (doc.frontmatter.legacyRedirects || []).concat(
doc.frontmatter.legacyRedirectsGenerated || [],
),
actions,
});
const navLinks = learn.filter(
(node) => node.fields.topic === doc.fields.topic,
);
actions.createPage({
path: doc.fields.path,
component: require.resolve("./src/templates/learn-doc.js"),
context: {
nodeId: doc.id,
frontmatter: doc.frontmatter,
pagePath: doc.fields.path,
navLinks: navLinks,
prevNext,
productVersions,
navTree,
},
});
(doc.frontmatter.katacodaPages || []).forEach((katacodaPage) => {
if (!katacodaPage.scenario || !katacodaPage.account) {
throw new Error(
`katacoda scenario or account missing for ${doc.fields.path}`,
);
}
const path = `${doc.fields.path}${katacodaPage.scenario}`;
actions.createPage({
path: path,
component: require.resolve("./src/templates/katacoda-page.js"),
context: {
...katacodaPage,
pagePath: path,
learn: {
title: doc.frontmatter.title,
description: doc.frontmatter.description,
},
},
});
});
};
/**
*
* @param {PublicFile} fileNodes Nodes to process
* @param {Array} productVersions sorted versions for each product - used to find "latest"
* @param {*} actions Gatsby actions
* @description Processes public file nodes, ensures that "latest" does something useful
*/
const processFileNodes = (fileNodes, productVersions, actions) => {
for (const node of fileNodes) {
const { relativePath } = node.parent;
const { urlPath, product, version } = node;
const isLatest =
product && productVersions[product]
? productVersions[product][0] === version
: false;
if (!isLatest) continue;
let prodVersionPath = path.join(path.sep, product, relativePath);
const latestPath = urlPath.replace(
prodVersionPath,
replacePathVersion(prodVersionPath),
);
if (latestPath === urlPath) continue;
const publicPath = path.join(process.cwd(), `public`, urlPath);
const publicLatestPath = path.join(process.cwd(), `public`, latestPath);
try {
realFs.mkdirSync(path.dirname(publicLatestPath), { recursive: true });
realFs.copyFileSync(publicPath, publicLatestPath);
} catch (err) {
console.error(
`error copying file from ${publicPath} to ${publicLatestPath}`,
err,
);
}
}
};
exports.sourceNodes = async ({
actions: { createNode },
createNodeId,
createContentDigest,
}) => {
// create edb-git node
createNode({
...gitData,
id: createNodeId("edb-git"),
internal: {
type: "edbGit",
contentDigest: createContentDigest(gitData),
},
});
};
exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
type Mdx implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
description: String
prevNext: Boolean
iconName: String
product: String
platform: String
originalFilePath: String
indexCards: TileModes
editTarget: EditTargets
legacyRedirects: [String]
legacyRedirectsGenerated: [String]
showInteractiveBadge: Boolean
hideToC: Boolean
deepToC: Boolean
hideVersion: Boolean
hideKBLink: Boolean
displayBanner: String
directoryDefaults: DirectoryDefaults
}
enum TileModes {
none
simple
full
}
enum EditTargets {
github
originalFilePath
none
}
type DirectoryDefaults {
description: String
prevNext: Boolean
iconName: String
product: String
platform: String
indexCards: TileModes
editTarget: EditTargets
showInteractiveBadge: Boolean
hideVersion: Boolean
hideKBLink: Boolean
displayBanner: String
}
type PublicFile implements Node {
absolutePath: String
urlPath: String
product: String
version: String
mimeType: String
ext: String
extension: String
}
`;
createTypes(typeDefs);
};
exports.onPreBootstrap = () => {
console.log(`
_____ ____ _____ ____
| __|| \\ | __ | | \\ ___ ___ ___
| __|| | || __ -| | | || . || _||_ -|
|_____||____/ |_____| |____/ |___||___||___|
`);
};
exports.onPreBuild = () => {};
exports.onPostBuild = async ({ graphql, reporter, pathPrefix }) => {
//
// netlify config
//
realFs.copyFileSync(
path.join(__dirname, "/netlify.toml"),
path.join(__dirname, "/public/netlify.toml"),
);
//
// get rid of compilation hash - speeds up netlify deploys
//
const hashTimer = reporter.activityTimer("Removing compilation hashes");
hashTimer.start();
const { globby } = await import("globby");
const generatedHTML = await globby([
path.join(__dirname, "/public/**/*.html"),
]);
for (
let i = 0, filename;
i < generatedHTML.length, (filename = generatedHTML[i]);
++i
) {
hashTimer.setStatus(`${i + 1}/${generatedHTML.length}`);
let file = await readFile(filename);
file = file.replace(
/window\.___webpackCompilationHash="[^"]+"/,
'window.___webpackCompilationHash=""',
);
await writeFile(filename, file);
}
const appDataFilename = path.join(
__dirname,
"/public/page-data/app-data.json",
);
const appData = await readFile(appDataFilename);
await writeFile(
appDataFilename,
appData.replace(
/"webpackCompilationHash":"[^"]+"/,
'"webpackCompilationHash":""',
),
);
hashTimer.end();
//
// additional headers
//
const publicFileData = await graphql(`
query {
allPublicFile {
nodes {
urlPath
mimeType
product
version
parent {
... on File {
relativePath
}
}
}
}
allMdx {
nodes {
fields {
docType
product
version
}
}
}
}
`);
if (publicFileData.errors) {
reporter.panic(
"PublicFile header creation graphql query has errors!",
publicFileData.errors,
);
}
const productVersions = buildProductVersions(
publicFileData.data.allMdx.nodes,
);
const newHeaders = [];
for (const file of publicFileData.data.allPublicFile.nodes) {
const { urlPath, mimeType, product, version } = file;
const { relativePath } = file.parent;
if (!mimeType) continue;
newHeaders.push(`${pathPrefix}${urlPath}
content-type: ${mimeType}`);
const isLatest =
product && productVersions[product]
? productVersions[product][0] === version
: false;
if (!isLatest) continue;
let prodVersionPath = path.join(path.sep, product, relativePath);
const latestPath = urlPath.replace(
prodVersionPath,
replacePathVersion(prodVersionPath),
);
if (latestPath === urlPath) continue;
newHeaders.push(`${pathPrefix}${latestPath}
content-type: ${mimeType}`);
}
await writeFile(
"public/_headers",
(await readFile("public/_headers")) + "\n" + newHeaders.join("\n"),
);
//
// redirects cleanup
//
const originalRedirects = await readFile("public/_redirects");
// rewrite legacy redirects to exclude the /docs prefix
const prefixRE = new RegExp(`^${pathPrefix}/edb-docs/`);
let rewrittenRedirects = originalRedirects
.split("\n")
.map((line) => line.replace(prefixRE, "/edb-docs/"))
.join("\n");
if (rewrittenRedirects.length === originalRedirects.length) {
reporter.warn("no legacy redirects were rewritten, did something change?");
}
await writeFile(
"public/_redirects",
`${rewrittenRedirects}
# Catch-all legacy redirects
/edb-docs/d/edb-backup-and-recovery-tool/* /docs/bart/latest/ 301
/edb-docs/d/edb-postgres-enterprise-manager/* /docs/pem/latest/ 301
/edb-docs/d/edb-postgres-advanced-server/* /docs/epas/latest/ 301
/edb-docs/d/postgresql/* /docs/supported-open-source/postgresql/ 301
/edb-docs/d/edb-postgres-failover-manager/* /docs/efm/latest/ 301
/edb-docs/d/edb-postgres-replication-server/* /docs/eprs/latest/ 301
/edb-docs/d/pgadmin-4/* /docs/supported-open-source/pgadmin/ 301
/edb-docs/d/edb-postgres-language-pack/* /docs/epas/latest/language_pack/ 301
/edb-docs/d/edb-postgres-migration-toolkit/* /docs/migration_toolkit/latest/ 301
/edb-docs/d/edb-postgres-migration-portal/* /docs/migration_portal/latest/ 301
/edb-docs/d/edb-postgres-hadoop-data-adapter/* /docs/hadoop_data_adapter/latest/ 301
/edb-docs/d/jdbc-connector/* /docs/jdbc_connector/latest/ 301
/edb-docs/d/edb-postgres-ocl-connector/* /docs/ocl_connector/latest/ 301
/edb-docs/d/edb-postgres-net-connector/* /docs/net_connector/latest/ 301
/edb-docs/d/edb-postgres-odbc-connector/* /docs/odbc_connector/latest/ 301
/edb-docs/p/edb-postgres-advanced-server/* /docs/epas/latest/ 301
/edb-docs/p/postgresql/* /docs/supported-open-source/postgresql/ 301
/edb-docs/p/edb-postgres-replication-server/* /docs/eprs/latest/ 301
/edb-docs/p/edb-postgres-failover-manager/* /docs/efm/latest/ 301
/edb-docs/p/pgadmin-4/* /docs/supported-open-source/pgadmin/ 301
/edb-docs/p/edb-postgres-migration-toolkit/* /docs/migration_toolkit/latest/ 301
/edb-docs/p/edb-postgres-hadoop-data-adapter/* /docs/hadoop_data_adapter/latest/ 301
/edb-docs/p/edb-postgres-language-pack/* /docs/epas/latest/language_pack/ 301
/edb-docs/p/jdbc-connector/* /docs/jdbc_connector/latest/ 301
/edb-docs/p/edb-postgres-net-connector/* /docs/net_connector/latest/ 301
/edb-docs/p/edb-postgres-slony-replication/* /docs/slony/latest/ 301
/edb-docs/p/pgpool-ii/* /docs/pgpool/latest/ 301
/edb-docs/p/edb-postgres-mysql-data-adapter/* /docs/mysql_data_adapter/latest/ 301
/edb-docs/p/edb-postgres-postgis/* /docs/postgis/latest/ 301
/edb-docs/p/pgbouncer/* /docs/pgbouncer/latest/ 301
/edb-docs/p/edb-postgres-mongodb-data-adapter/* /docs/mongo_data_adapter/latest/ 301
/edb-docs/p/edb-postgres-migration-portal/* /docs/migration_portal/latest/ 301
/edb-docs/p/edb-postgres-enterprise-manager/* /docs/pem/latest/ 301
/edb-docs/p/edbplus/* /docs/edb_plus/latest/ 301
/edb-docs/p/edb-postgres-odbc-connector/* /docs/odbc_connector/latest/ 301
/edb-docs/p/edb-postgres-ocl-connector/* /docs/ocl_connector/latest/ 301
/edb-docs/p/edb-backup-and-recovery-tool/* /docs/bart/latest/ 301
/edb-docs/* /docs/ 301
# Netlify pathPrefix path rewrite
${pathPrefix}/* /:splat 200`,
);
};