-
Notifications
You must be signed in to change notification settings - Fork 794
Expand file tree
/
Copy pathpage-utils.ts
More file actions
760 lines (669 loc) · 20.2 KB
/
page-utils.ts
File metadata and controls
760 lines (669 loc) · 20.2 KB
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
751
752
753
754
755
756
757
758
759
760
import { processDirectoryForYaml } from "@/server/processor/yaml";
import {
processDirectoryForMarkDown,
ProcessedFile,
FilterCriteria as MdxFilterCriteria,
} from "@/server/processor/mdx";
import { processDirectoryForJson } from "@/server/processor/json";
import { CommandType } from "@/components/common/commands/types";
const filterMdxFiles = (
files: ProcessedFile[],
filter: MdxFilterCriteria = {}
): ProcessedFile[] => {
return files.filter((file) => {
if (filter.fileAbsolutePath) {
if (
filter.fileAbsolutePath.ne &&
file.fileAbsolutePath === filter.fileAbsolutePath.ne
) {
return false;
}
if (filter.fileAbsolutePath.regex) {
const regex = new RegExp(filter.fileAbsolutePath.regex);
if (!regex.test(file.fileAbsolutePath)) {
return false;
}
}
}
if (filter.fields) {
for (const [fieldName, fieldFilter] of Object.entries(filter.fields)) {
if (!file.fields[fieldName]) {
if (fieldFilter.ne !== null) {
return false;
}
} else if (
fieldFilter.ne &&
file.fields[fieldName] === fieldFilter.ne
) {
return false;
}
}
}
if (filter.frontmatter) {
for (const [fieldName, fieldFilter] of Object.entries(
filter.frontmatter
)) {
if (!file.frontmatter[fieldName]) {
// If field doesn't exist and ne is defined, we should include the file
// (since ne means "not equal", and undefined is not equal to the ne value)
return true;
} else if (
fieldFilter.ne &&
file.frontmatter[fieldName] === fieldFilter.ne
) {
return false;
}
}
}
return true;
});
};
// Type definitions for different page data structures
export interface GuideData {
guide: ProcessedFile;
prev: { fields: { slug: string; guide_directory: string } } | null;
next: { fields: { slug: string; guide_directory: string } } | null;
}
export interface DocData {
doc: ProcessedFile;
}
export interface TerminusCommandData extends CommandType {
slug: string;
}
export interface ReleaseNoteData {
prev: { fields: { slug: string } } | null;
node: ProcessedFile;
next: { fields: { slug: string } } | null;
}
export interface ReleaseNoteListingData {
pageNumber: number;
releaseNotes: ReleaseNoteData[];
categories: {
node: {
frontmatter: {
categories: string[];
};
};
}[];
totalPages: number;
}
export interface IframeEmbedData {
iframeEmbed: ProcessedFile;
}
export interface LandingData {
landing: any; // Using any for now since the landing structure is complex and varies
}
// Base interface for common PageData properties without Component
export interface BasePageDataWithoutComponent {
uri: string;
title: string;
relativeFilePath: string;
description: string;
rawFileData: string;
}
// Union type for PageData without Component
export type PageDataWithoutComponent =
| (BasePageDataWithoutComponent & { type: "guide"; data: GuideData })
| (BasePageDataWithoutComponent & { type: "doc"; data: DocData })
| (BasePageDataWithoutComponent & {
type: "terminus-command";
data: TerminusCommandData;
})
| (BasePageDataWithoutComponent & {
type: "release-note";
data: ReleaseNoteData;
})
| (BasePageDataWithoutComponent & {
type: "release-note-listing";
data: ReleaseNoteListingData;
})
| (BasePageDataWithoutComponent & {
type: "iframe-embed";
data: IframeEmbedData;
})
| (BasePageDataWithoutComponent & { type: "landing"; data: LandingData });
// Legacy interface for backward compatibility (includes Component)
export interface BasePageData extends BasePageDataWithoutComponent {
Component: React.ReactNode;
}
// Legacy union type for backward compatibility
export type PageData = PageDataWithoutComponent & {
Component: React.ReactNode;
};
export const normalizeSlug = (slug: string): string => {
let normalizedSlug = slug;
if (normalizedSlug.startsWith("/")) {
normalizedSlug = normalizedSlug.slice(1);
}
if (normalizedSlug.endsWith("/")) {
normalizedSlug = normalizedSlug.slice(0, -1);
}
return normalizedSlug;
};
export const processDocPages = async (
uri?: string[]
): Promise<PageDataWithoutComponent[]> => {
const allContentFiles = processDirectoryForMarkDown("source", {});
const filteredDocs = filterMdxFiles(allContentFiles, {
fileAbsolutePath: {
regex:
"/content(?!/(partials|changelog|guides|releasenotes|iframeembeds)/)/",
},
frontmatter: {
draft: { ne: true },
},
});
const pages: PageDataWithoutComponent[] = [];
const targetUri = uri?.join("/");
for (const doc of filteredDocs) {
const slug = normalizeSlug(doc.fields.slug);
// If looking for specific URI and this doesn't match, skip
if (targetUri && slug !== targetUri) {
continue;
}
pages.push({
uri: slug,
title: doc.frontmatter.subtitle ?? doc.frontmatter.title ?? "Doc",
description: doc.frontmatter.description ?? "Doc",
type: "doc",
data: { doc },
rawFileData: doc.internal.content,
relativeFilePath: doc.relativePath,
});
// If looking for specific URI and found it, return early
if (targetUri && slug === targetUri) {
return pages;
}
}
return pages;
};
export const processGuidePages = async (
uri?: string[]
): Promise<PageDataWithoutComponent[]> => {
const guides = processDirectoryForMarkDown("source/content/guides", {
sortBy: "fileAbsolutePath",
sortOrder: "asc",
});
const updatedGuides = guides.reduce(
(acc, guide, index) => {
return [
...acc,
{
prev:
index > 0
? guides[index - 1].fields.guide_directory !==
guide.fields.guide_directory
? null
: {
fields: {
slug: guides[index - 1].fields.slug,
guide_directory: guides[index - 1].fields.guide_directory,
},
}
: null,
next:
index < guides.length - 1
? guides[index + 1].fields.guide_directory !==
guide.fields.guide_directory
? null
: {
fields: {
slug: guides[index + 1].fields.slug,
guide_directory: guides[index + 1].fields.guide_directory,
},
}
: null,
guide,
},
];
},
[] as {
guide: ProcessedFile;
prev: { fields: { slug: string; guide_directory: string } } | null;
next: { fields: { slug: string; guide_directory: string } } | null;
}[]
);
const pages: PageDataWithoutComponent[] = [];
const targetUri = uri?.join("/");
for (const guideContent of updatedGuides) {
const slug = normalizeSlug(guideContent.guide.fields.slug);
// If looking for specific URI and this doesn't match, skip
if (targetUri && slug !== targetUri) {
continue;
}
pages.push({
uri: slug,
title:
guideContent.guide.frontmatter.subtitle ??
guideContent.guide.frontmatter.title ??
"Guide",
description: guideContent.guide.frontmatter.description ?? "Guide",
type: "guide",
data: {
guide: guideContent.guide,
prev: guideContent.prev,
next: guideContent.next,
},
rawFileData: guideContent.guide.internal.content,
relativeFilePath: guideContent.guide.relativePath,
});
// If looking for specific URI and found it, return early
if (targetUri && slug === targetUri) {
return pages;
}
}
return pages;
};
export const processTerminusCommandPages = async (
uri?: string[]
): Promise<PageDataWithoutComponent[]> => {
const terminusCommands = (
await processDirectoryForJson("source/data", "commands.json")
)?.[0]?.content as {
commands: CommandType[];
};
const commands = terminusCommands.commands.map((command) => {
const slugRegExp = /:/g;
const slug = command.name.replace(slugRegExp, "-");
return {
...command,
slug: `terminus/commands/${slug}`,
};
});
const pages: PageDataWithoutComponent[] = [];
const targetUri = uri?.join("/");
for (const terminusCommand of commands) {
// If looking for specific URI and this doesn't match, skip
if (targetUri && terminusCommand.slug !== targetUri) {
continue;
}
pages.push({
uri: terminusCommand.slug,
title: `${terminusCommand.name}`,
description: `${terminusCommand.description}`,
type: "terminus-command",
data: terminusCommand,
rawFileData: JSON.stringify(terminusCommands),
relativeFilePath: "src/source/data/commands.json",
});
// If looking for specific URI and found it, return early
if (targetUri && terminusCommand.slug === targetUri) {
return pages;
}
}
return pages;
};
export const getAllReleaseNotes = () => {
const releaseNotes = processDirectoryForMarkDown("source/releasenotes", {
sortBy: "fileAbsolutePath",
sortOrder: "desc",
});
return releaseNotes;
};
export const processReleaseNotePages = async (
uri?: string[],
selectedCategories?: string[]
): Promise<PageDataWithoutComponent[]> => {
const releaseNotes = getAllReleaseNotes();
const allReleaseNotes = releaseNotes.reduce(
(acc, releaseNote) => {
return [
...acc,
{
prev:
acc.length > 0
? {
fields: {
slug: releaseNotes[acc.length - 1].fields.slug,
},
}
: null,
node: releaseNote,
next:
acc.length < releaseNotes.length - 1
? {
fields: {
slug: releaseNotes[acc.length + 1].fields.slug,
},
}
: null,
},
];
},
[] as {
prev: { fields: { slug: string } } | null;
node: ProcessedFile;
next: { fields: { slug: string } } | null;
}[]
);
const pages: PageDataWithoutComponent[] = [];
const targetUri = uri?.join("/");
// Filter the release notes
const filteredReleaseNotes = allReleaseNotes.filter((releaseNote) => {
if (!selectedCategories || selectedCategories.length === 0) {
return true;
}
const noteCategories = releaseNote.node.frontmatter.categories || [];
return noteCategories.some((cat: string) => selectedCategories.includes(cat));
});
// Add individual release note pages
for (const releaseNote of filteredReleaseNotes) {
if (targetUri && releaseNote.node.fields.slug !== targetUri) {
continue;
}
pages.push({
uri: releaseNote.node.fields.slug,
title: releaseNote.node.frontmatter.title ?? "Release Note",
description: releaseNote.node.frontmatter.description ?? "Release Note",
type: "release-note",
data: releaseNote,
rawFileData: releaseNote.node.internal.content,
relativeFilePath: releaseNote.node.relativePath,
});
// If looking for specific URI and found it, return early
if (targetUri && releaseNote.node.fields.slug === targetUri) {
return pages;
}
}
// Add paginated release note pages
const releaseNotesPostsPerPage = 8;
const releaseNotesNumPages = Math.ceil(
filteredReleaseNotes.length / releaseNotesPostsPerPage
);
for (let i = 0; i < releaseNotesNumPages; i++) {
const path = `release-notes/${i + 1}`;
// If looking for specific URI and this doesn't match, skip
if (targetUri && path !== targetUri) {
continue;
}
const releaseNotes = filteredReleaseNotes.slice(
i * releaseNotesPostsPerPage,
(i + 1) * releaseNotesPostsPerPage
);
const categories = filteredReleaseNotes.map((releaseNote) => {
return {
node: {
frontmatter: {
categories: releaseNote.node.frontmatter.categories ?? [],
},
},
};
});
pages.push({
uri: path,
title: "Release Notes",
description: "Release Notes",
type: "release-note-listing",
data: {
releaseNotes,
categories,
totalPages: releaseNotesNumPages,
pageNumber: i + 1,
},
rawFileData: JSON.stringify(releaseNotes),
relativeFilePath: "src/source/releasenotes/index.md",
});
// If looking for specific URI and found it, return early
if (targetUri && path === targetUri) {
return pages;
}
}
return pages;
};
export const processIframeEmbedPages = async (
uri?: string[]
): Promise<PageDataWithoutComponent[]> => {
const iframeEmbeds = processDirectoryForMarkDown(
"source/content/iframeembeds"
);
const pages: PageDataWithoutComponent[] = [];
const targetUri = uri?.join("/");
for (const iframeEmbed of iframeEmbeds) {
const iframeUri = `iframeembeds/${iframeEmbed.fields.slug}`;
// If looking for specific URI and this doesn't match, skip
if (targetUri && iframeUri !== targetUri) {
continue;
}
iframeEmbed.fields.slug = iframeUri;
pages.push({
uri: iframeUri,
title: iframeEmbed.frontmatter.title ?? "Iframe Embed",
description: iframeEmbed.frontmatter.description ?? "Iframe Embed",
type: "iframe-embed",
data: { iframeEmbed },
rawFileData: iframeEmbed.internal.content,
relativeFilePath: iframeEmbed.relativePath,
});
// If looking for specific URI and found it, return early
if (targetUri && iframeUri === targetUri) {
return pages;
}
}
return pages;
};
export const processLandingPages = async (
uri?: string[]
): Promise<PageDataWithoutComponent[]> => {
const landings = processDirectoryForYaml("source/data", {
filter: (filePath) => filePath.includes("source/data/landings.yaml"),
})[0];
const landingsContent = landings.content as any[];
const pages: PageDataWithoutComponent[] = [];
const targetUri = uri?.join("/");
for (const landing of landingsContent) {
// If looking for specific URI and this doesn't match, skip
if (targetUri && landing.path !== targetUri) {
continue;
}
pages.push({
uri: landing.path,
title: landing.title,
description: landing.description,
type: "landing",
data: { landing },
rawFileData: JSON.stringify(landing),
relativeFilePath: "src/source/data/landings.yaml",
});
// If looking for specific URI and found it, return early
if (targetUri && landing.path === targetUri) {
return pages;
}
}
return pages;
};
export const getReleaseNotesByCategories = async (
uri?: string[],
selectedCategories?: string[]
): Promise<PageDataWithoutComponent[]> => {
// If URI is specified, run functions in sequence and return early when match is found
if (uri) {
const releaseNotePages = await processReleaseNotePages(uri);
const filteredReleaseNotes = releaseNotePages.filter((page) => { return true});
if (filteredReleaseNotes.length > 0) return filteredReleaseNotes;
}
return [];
}
export const getAllPages = async (
uri?: string[],
selectedCategories?: string[]
): Promise<PageDataWithoutComponent[]> => {
// If URI is specified, run functions in sequence and return early when match is found
if (uri) {
// Try each content type in sequence
const docPages = await processDocPages(uri);
if (docPages.length > 0) return docPages;
const guidePages = await processGuidePages(uri);
if (guidePages.length > 0) return guidePages;
const terminusCommandPages = await processTerminusCommandPages(uri);
if (terminusCommandPages.length > 0) return terminusCommandPages;
const releaseNotePages = await processReleaseNotePages(uri, selectedCategories);
if (releaseNotePages.length > 0) return releaseNotePages;
const iframeEmbedPages = await processIframeEmbedPages(uri);
if (iframeEmbedPages.length > 0) return iframeEmbedPages;
const landingPages = await processLandingPages(uri);
if (landingPages.length > 0) return landingPages;
// If no match found, return empty array
return [];
}
// If no URI specified, return all pages (parallel processing for performance)
const [
docPages,
guidePages,
terminusCommandPages,
releaseNotePages,
iframeEmbedPages,
landingPages,
] = await Promise.all([
processDocPages(),
processGuidePages(),
processTerminusCommandPages(),
processReleaseNotePages(),
processIframeEmbedPages(),
processLandingPages(),
]);
return [
...docPages,
...guidePages,
...terminusCommandPages,
...releaseNotePages,
...iframeEmbedPages,
...landingPages,
];
};
export const fetchArticleById = async (id: string) => {
const query = `
query GetArticle($id: String, $contentType: ContentType, $publishingLevel: PublishingLevel) {
article(id: $id, contentType: $contentType, publishingLevel: $publishingLevel) {
id
title
content
slug
tags
siteId
metadata
publishedDate
publishingLevel
contentType
updatedAt
previewActiveUntil
}
}
`;
const variables = {
id: id,
contentType: "TEXT_MARKDOWN",
publishingLevel: "PRODUCTION",
};
try {
const response = await fetch(
`${process.env.PCC_HOST || "https://gql.prod.pcc.pantheon.io"}/sites/${process.env.PCC_SITE_ID}/query`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"PCC-TOKEN": process.env.PCC_TOKEN || "",
},
body: JSON.stringify({
query,
variables,
}),
}
);
if (!response.ok) {
const error = await response.text();
throw new Error(`HTTP error! status: ${response.status} ${error} ${id}`);
}
const data = await response.json();
return data.data.article;
} catch (error) {
console.error("Fetch error:", error);
throw error;
}
};
// Using fetch with the same GraphQL query
export const fetchArticleBySlug = async (
slug: string,
siteId: string = process.env.PCC_SITE_ID || "",
token: string = process.env.PCC_TOKEN || "",
options: { withContent: boolean; withMetadata: boolean } = {
withContent: true,
withMetadata: true,
},
tries: number = 2
) => {
console.debug("fetching article by slug", slug);
const query = `
query GetArticle($slug: String, $contentType: ContentType, $publishingLevel: PublishingLevel) {
article(slug: $slug, contentType: $contentType, publishingLevel: $publishingLevel) {
id
title
${options.withContent === true ? "content" : ""}
slug
tags
siteId
${options.withMetadata === true ? "metadata" : ""}
publishedDate
publishingLevel
contentType
updatedAt
previewActiveUntil
}
}
`;
const variables = {
slug: slug,
contentType: "TEXT_MARKDOWN",
publishingLevel: "PRODUCTION",
};
while (tries > 0) {
tries -= 1;
try {
const response = await fetch(
`${process.env.PCC_HOST || "https://gql.prod.pcc.pantheon.io"}/sites/${siteId}/query`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"PCC-TOKEN": token,
},
body: JSON.stringify({
query,
variables,
}),
}
);
if (!response.ok) {
if (response.status === 404) {
return null;
}
const error = await response.text();
throw new Error(
`HTTP error! status: ${response.status} ${error} ${slug}`
);
}
const data = await response.json();
return data.data.article;
} catch (error) {
console.error("Fetch error:", error, { tries });
if (tries === 0) {
throw error;
}
}
}
};
export const singleSlugForFetch = (slug: string) => {
if (slug.startsWith("_")) {
slug = slug.slice(1);
}
return slug
.replaceAll("/", "-")
.replaceAll("_", "-")
.replaceAll(".", "-")
.replaceAll(" ", "-")
.replaceAll("-&-", "-")
.replaceAll(",-", "-")
.replaceAll("!", "")
.replaceAll("(", "")
.replaceAll(")", "")
.toLowerCase();
};