-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
page_preparer.ts
239 lines (197 loc) Β· 5.89 KB
/
page_preparer.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
import { parseISO } from "../deps/date.ts";
import { posix } from "../deps/path.ts";
import { Exception } from "./errors.ts";
import { Page } from "./filesystem.ts";
import { getExtension } from "./utils.ts";
import type { Data, Directory, PageData } from "../core.ts";
export interface Options {
/** The full path of the src folder */
src: string;
/** Pretty urls configuration */
prettyUrls: boolean;
}
/**
* Class to prepare pages before rendering, completing the missing data
*/
export default class pagePreparer {
src: string;
prettyUrls: boolean;
constructor(options: Options) {
this.src = options.src;
this.prettyUrls = options.prettyUrls;
}
/** Returns the final URL assigned to a page */
getUrl(page: Page, parentPath: string): string | false {
const { data } = page;
let url = data.url as
| string
| ((page: Page) => string | false)
| false
| undefined;
if (url === false) {
return false;
}
if (typeof url === "function") {
url = url(page);
}
if (typeof url === "string") {
// Relative URL
if (url.startsWith("./") || url.startsWith("../")) {
return normalizeUrl(posix.join(parentPath, url));
}
if (url.startsWith("/")) {
return normalizeUrl(url);
}
throw new Exception(
`The url variable must start with "/", "./" or "../"`,
{ page, url },
);
}
// If the user has provided a value which hasn't yielded a string then it is an invalid url.
if (url !== undefined) {
throw new Exception(
`If a url is specified, it should either be a string, or a function which returns a string. The provided url is of type: ${typeof url}.`,
{ page, url },
);
}
// Calculate the URL from the path
url = posix.join(parentPath, page.src.slug);
const ext = getExtension(page.src.path);
if (ext) {
return url + ext;
}
if (page.src.asset) {
return url + page.src.ext;
}
if (this.prettyUrls) {
if (posix.basename(url) === "index") {
return posix.join(posix.dirname(url), "/");
}
return posix.join(url, "/");
}
return `${url}.html`;
}
/** Returns the date assigned to a page */
getDate(page: Page): Date {
const { data } = page;
const date = data.date as Date | undefined | number | string;
if (date instanceof Date) {
return date;
}
if (!date) {
return page.src.created ?? page.src.lastModified ?? new Date();
}
if (typeof date === "number") {
return new Date(date);
}
if (typeof date === "string") {
switch (date.toLowerCase()) {
case "git last modified":
return getGitDate(
"modified",
posix.join(this.src, page.src.path + page.src.ext),
) || page.src.lastModified || new Date();
case "git created":
return getGitDate(
"created",
posix.join(this.src, page.src.path + page.src.ext),
) || page.src.created || new Date();
}
const parsed = parseISO(date, {});
if (!isNaN(parsed.getTime())) {
return parsed;
}
}
throw new Exception("Invalid date.", { page });
}
/** Return the data associated with a page or folder */
getData(
entry: Page | Directory,
parentData: Data,
globalData?: Map<string, Data>,
): PageData {
const global = globalData?.get(entry.src.path + (entry.src.ext || ""));
if (global) {
parentData = mergeData(parentData, global);
}
const data = mergeData(parentData, entry.baseData);
if (entry instanceof Page) {
data.page = entry;
}
return data as PageData;
}
}
/** Merge the cascade data */
export function mergeData(parentData: Data, baseData: Data): Data {
const data: Data = { ...parentData, ...baseData };
// Merge special keys
const mergedKeys: Record<string, string> = {
...parentData.mergedKeys,
...baseData.mergedKeys,
};
for (const [key, type] of Object.entries(mergedKeys)) {
switch (type) {
case "stringArray":
case "array":
{
const baseValue: unknown[] = Array.isArray(baseData[key])
? baseData[key] as unknown[]
: (key in baseData)
? [baseData[key]]
: [];
const parentValue: unknown[] = Array.isArray(parentData[key])
? parentData[key] as unknown[]
: (key in parentData)
? [parentData[key]]
: [];
const merged = [...parentValue, ...baseValue];
data[key] = [
...new Set(
type === "stringArray" ? merged.map(String) : merged,
),
];
}
break;
case "object":
{
const baseValue = baseData[key] as
| Record<string, unknown>
| undefined;
const parentValue = parentData[key] as
| Record<string, unknown>
| undefined;
data[key] = { ...parentValue, ...baseValue };
}
break;
}
}
return data;
}
/**
* Returns the result of a git command as Date
* Thanks to https://github.com/11ty/eleventy/blob/8dd2a1012de92c5ee1eab7c37e6bf1b36183927e/src/Util/DateGitLastUpdated.js
*/
export function getGitDate(
type: "created" | "modified",
file: string,
): Date | undefined {
const args = type === "created"
? ["log", "--diff-filter=A", "--follow", "-1", "--format=%at", "--", file]
: ["log", "-1", "--format=%at", "--", file];
const { code, stdout } = new Deno.Command("git", { args }).outputSync();
if (code !== 0) {
return;
}
const str = new TextDecoder().decode(stdout);
const timestamp = parseInt(str) * 1000;
if (timestamp) {
return new Date(timestamp);
}
}
/** Remove the /index.html part if exist */
export function normalizeUrl(url: string): string {
if (url.endsWith("/index.html")) {
return url.slice(0, -10);
}
return url;
}