-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
97 lines (79 loc) · 2.78 KB
/
main.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
import { serve } from "std/http/server.ts";
import * as Snippets from "./rulegen/rules.ts";
import SystemRules from "./rulegen/rules/system.ts";
import { LSRules, Snippet } from "./rulegen/types.ts";
import { prefix } from "./rulegen/utils.ts";
const PREFIXES = new Map([
["homebrew", "/Applications/Homebrew"],
["home", "~/Applications"],
]);
const snippets = new Map<string, Snippet>();
const prefixedSnippets = new Map<string, Snippet>();
const defaultPrefixedSnippets = new Array<Snippet>();
// Import all rule snippets.
for (const [_key, value] of Object.entries(Snippets)) {
snippets.set(value.metadata.id, value);
if (value.metadata.properties?.canHavePrefix) {
PREFIXES.forEach((path, id) => {
const snippet = prefix(value, path, id);
prefixedSnippets.set(snippet.metadata.id, snippet);
});
const defaultPrefix = value.metadata.properties.defaultPrefix;
defaultPrefixedSnippets.push(
defaultPrefix
? prefix(value, PREFIXES.get(defaultPrefix)!, defaultPrefix)
: value,
);
} else {
defaultPrefixedSnippets.push(value);
}
}
// Main HTTP server.
serve((req) => {
const url = new URL(req.url);
// System rules are handled as a separate endpoint.
if (url.pathname === "/system") {
return Response.json(SystemRules);
}
// Aggregate endpoint for all apps.
if (url.pathname === "/all") {
const data: LSRules = {
name: "Applications",
description: "Includes rules for various 3rd-party apps.",
rules: Array.from(snippets.values())
.map((s) => s.rules)
.flat(),
};
return Response.json(data);
}
// Endpoint for prefixed apps (Homebrew apps in /Applications/Homebrew, everything else in /Applications).
if (url.pathname === "/all-prefixed") {
const data: LSRules = {
name: "Applications",
description:
"Includes rules for various 3rd-party apps (from Homebrew and user's home directory).",
rules: defaultPrefixedSnippets.map((s) => s.rules).flat(),
};
return Response.json(data);
}
// Pick-and-choose endpoint.
if (url.pathname !== "/") {
const ids = url.pathname.substring(1).split("+");
const selected = ids.map(
(id) => snippets.get(id) || prefixedSnippets.get(id),
);
if (selected.some((s) => !s)) {
return new Response("one of the apps was not found", { status: 404 });
}
const rules = selected.map((s) => s!.rules).flat();
const names = selected.map((s) => s!.metadata.name).join(", ");
const data: LSRules = {
name: "Applications",
description: `Includes rules for the following 3rd-party apps: ${names}.`,
rules,
};
return Response.json(data);
}
// By default, redirect to all rules endpoint. TODO: user interface
return Response.redirect(`${url.origin}/all`);
});