-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathparser.ts
More file actions
217 lines (182 loc) · 5.61 KB
/
parser.ts
File metadata and controls
217 lines (182 loc) · 5.61 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
import YAML from "yaml";
import { z } from "zod";
import { t } from "@/i18n";
import { GroupVariant, type Query, ShowMetadataVariant, SortingVariant } from "@/query/query";
type ErrorTree = string | { msg: string; children: ErrorTree[] };
function formatErrorTree(tree: ErrorTree, indent = ""): string {
if (typeof tree === "string") {
return `${indent}${tree}`;
}
const lines = [`${indent}${tree.msg}`];
for (const child of tree.children) {
lines.push(formatErrorTree(child, `${indent} `));
}
return lines.join("\n");
}
export class ParsingError extends Error {
messages: ErrorTree[];
inner: unknown | undefined;
constructor(msgs: ErrorTree[], inner: unknown | undefined = undefined) {
super(msgs.map((tree) => formatErrorTree(tree)).join("\n"));
this.inner = inner;
this.messages = msgs;
}
public toString(): string {
if (this.inner) {
return `${this.message}: '${this.inner}'`;
}
return super.toString();
}
}
export type QueryWarning = string;
export function parseQuery(raw: string): [Query, QueryWarning[]] {
let obj: Record<string, unknown> | null = null;
const warnings: QueryWarning[] = [];
try {
obj = tryParseAsJson(raw);
warnings.push(t().query.warning.jsonQuery);
} catch {
try {
obj = tryParseAsYaml(raw);
} catch {
throw new ParsingError(["Unable to parse as YAML or JSON"]);
}
}
if (obj === null) {
obj = {};
}
const [query, parsingWarnings] = parseObjectZod(obj);
warnings.push(...parsingWarnings);
return [query, warnings];
}
function tryParseAsJson(raw: string): Record<string, unknown> {
try {
return JSON.parse(raw);
} catch (e) {
throw new ParsingError(["Invalid JSON"], e);
}
}
function tryParseAsYaml(raw: string): Record<string, unknown> {
try {
return YAML.parse(raw);
} catch (e) {
throw new ParsingError(["Invalid YAML"], e);
}
}
const lookupToEnum = <T>(lookup: Record<string, T>) => {
const keys = Object.keys(lookup);
return z.enum(keys).transform((key) => lookup[key]);
};
const sortingSchema = lookupToEnum({
priority: SortingVariant.Priority,
priorityAscending: SortingVariant.PriorityAscending,
priorityDescending: SortingVariant.Priority,
date: SortingVariant.Date,
dateAscending: SortingVariant.Date,
dateDescending: SortingVariant.DateDescending,
order: SortingVariant.Order,
dateAdded: SortingVariant.DateAdded,
dateAddedAscending: SortingVariant.DateAdded,
dateAddedDescending: SortingVariant.DateAddedDescending,
alphabetical: SortingVariant.Alphabetical,
alphabeticalAscending: SortingVariant.Alphabetical,
alphabeticalDescending: SortingVariant.AlphabeticalDescending,
});
const showSchema = lookupToEnum({
due: ShowMetadataVariant.Due,
date: ShowMetadataVariant.Due,
description: ShowMetadataVariant.Description,
labels: ShowMetadataVariant.Labels,
project: ShowMetadataVariant.Project,
deadline: ShowMetadataVariant.Deadline,
time: ShowMetadataVariant.Time,
});
const groupBySchema = lookupToEnum({
project: GroupVariant.Project,
section: GroupVariant.Section,
priority: GroupVariant.Priority,
due: GroupVariant.Date,
date: GroupVariant.Date,
labels: GroupVariant.Label,
});
const defaults = {
name: "",
autorefresh: 0,
sorting: [SortingVariant.Order],
show: [
ShowMetadataVariant.Due,
ShowMetadataVariant.Description,
ShowMetadataVariant.Labels,
ShowMetadataVariant.Project,
ShowMetadataVariant.Deadline,
],
groupBy: GroupVariant.None,
};
const querySchema = z.object({
name: z.string().optional().default(""),
filter: z.string(),
autorefresh: z.number().nonnegative().optional().default(0),
sorting: z
.array(sortingSchema)
.optional()
.transform((val) => val ?? defaults.sorting),
show: z
.union([z.array(showSchema), z.literal("none").transform(() => [])])
.optional()
.transform((val) => val ?? defaults.show),
groupBy: groupBySchema.optional().transform((val) => val ?? defaults.groupBy),
});
const validQueryKeys: string[] = querySchema.keyof().options;
function parseObjectZod(query: Record<string, unknown>): [Query, QueryWarning[]] {
const warnings: QueryWarning[] = [];
for (const key of Object.keys(query)) {
if (!validQueryKeys.includes(key)) {
warnings.push(t().query.warning.unknownKey(key));
}
}
const out = querySchema.safeParse(query);
if (!out.success) {
throw new ParsingError(formatZodError(out.error));
}
const show = new Set(out.data.show);
if (show.has(ShowMetadataVariant.Due) && show.has(ShowMetadataVariant.Time)) {
warnings.push(t().query.warning.dueAndTime);
}
return [
{
name: out.data.name,
filter: out.data.filter,
autorefresh: out.data.autorefresh,
sorting: out.data.sorting,
show,
groupBy: out.data.groupBy,
},
warnings,
];
}
type QuerySchema = z.infer<typeof querySchema>;
function formatZodError(error: z.ZodError<QuerySchema>): ErrorTree[] {
const tree = z.treeifyError(error);
const errors: ErrorTree[] = [...tree.errors];
if (tree.properties === undefined) {
return errors;
}
for (const [key, child] of Object.entries(tree.properties)) {
if (child.errors.length > 0) {
errors.push({
msg: `Field '${key}' has the following issues:`,
children: child.errors,
});
}
if ("items" in child && child.items !== undefined) {
const root: ErrorTree = {
msg: `Field '${key}' elements have the following issues:`,
children: child.items.flatMap((item, idx) =>
item.errors.map((msg) => `Item '${key}[${idx}]': ${msg}`),
),
};
errors.push(root);
}
}
return errors;
}