-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
183 lines (153 loc) · 6.35 KB
/
Copy pathserver.ts
File metadata and controls
183 lines (153 loc) · 6.35 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
import simpleGit, { type SimpleGitOptions } from "simple-git";
import { sync, type Changes } from "aframe-watcher-bun";
// @ts-ignore
import aframeInspector from "./node_modules/aframe-inspector/dist/aframe-inspector.min.js" with { type: "text" };
// @ts-ignore
import aframeMin from "./node_modules/aframe/dist/aframe-master.min.js" with { type: "text" };
import { name as projectName } from "./package.json";
import { config } from "dotenv";
import { readdir } from "node:fs/promises";
import path from "path";
config();
const port = parseInt(process.env.PORT || "3000");
const PROJECT_DIR = process.env.PROJECT_DIR || "project";
const GIT_TEMPLATE_REPO = process.env.GIT_TEMPLATE_REPO || "https://github.com/bcopy/my-wonderland";
const GIT_TEMPLATE_BRANCH = process.env.GIT_TEMPLATE_BRANCH || "aframe-git-editor";
const GIT_REMOTE_URL = process.env.GIT_REMOTE_URL;
const GIT_AUTH_TOKEN = process.env.GIT_AUTH_TOKEN;
const SAVE_AUTH_REQUIRED = (process.env.SAVE_AUTH_REQUIRED || "false") === "true";
// Path resolution: CLI arg > ENV > Default ./index.html
const cliPath = process.argv[2];
const envPath = process.env.AFRAME_WATCHER_HTML;
const defaultPath = path.join(PROJECT_DIR, "/*.html");
let examplePath = cliPath || envPath || defaultPath;
const isDefault = !cliPath && !envPath;
const file = Bun.file(examplePath);
// If the PROJECT_DIR does not exist or is empty, clone the template repository
const projectPath = path.join(process.cwd(), PROJECT_DIR);
let projectDirExists = false;
let projectDirIsEmpty = true;
let isDirectory = false;
try {
const stats = await Bun.file(projectPath).stat();
projectDirExists = true;
isDirectory = stats.isDirectory();
if (isDirectory) {
const filesInProjectDir = await readdir(projectPath);
console.log(`Found ${filesInProjectDir.length} files in Project directory ${projectPath}.`);
projectDirIsEmpty = filesInProjectDir.length === 0;
}
} catch (error) {
console.log(`Project dir ${projectPath} does not exist or cannot be accessed.`);
projectDirExists = false;
isDirectory = false;
projectDirIsEmpty = true; // If it doesn't exist, it's considered empty for the cloning logic
}
if (!projectDirExists || projectDirIsEmpty) {
console.log(`[${projectName}] Project directory ${projectPath} not found or is empty. Exporting template...`);
const git = simpleGit();
// Export: clone with depth 1
await git.clone(GIT_TEMPLATE_REPO, PROJECT_DIR, [
"--depth", "1",
"--single-branch",
"--branch", GIT_TEMPLATE_BRANCH
]);
// Remove .git to reinitialize a fresh repository if needed
await Bun.$`rm -rf ${PROJECT_DIR}/.git`;
// Initialize a fresh repository only if GIT_REMOTE_URL is specified
if (GIT_REMOTE_URL) {
console.log(`[${projectName}] Initializing fresh git repository...`);
const projectGit = simpleGit(PROJECT_DIR);
await projectGit.init();
await projectGit.addRemote("origin", GIT_REMOTE_URL);
}
} else {
console.warn(`[${projectName}] Warning: Project directory ${PROJECT_DIR} already exists and is not empty. Skipping git export of template repository.`);
}
console.log(`[${projectName}] Starting A-Frame Bun Watcher on http://localhost:${port}...`);
console.log(`[${projectName}] Targeting file: ${examplePath}`);
export const serverOptions = {
port,
async fetch(req: Request) {
const url = new URL(req.url);
// 1. Serve static files from the PROJECT_DIR
if (url.pathname === "/") {
// Serve index.html from the project root
const indexFilePath = path.join(PROJECT_DIR, "index.html");
const indexFile = Bun.file(indexFilePath);
if (await indexFile.exists()) {
return new Response(indexFile, { headers: { "Content-Type": "text/html" } });
}
}
const filePath = path.join(PROJECT_DIR, url.pathname);
const file = Bun.file(filePath);
if (await file.exists()) {
return new Response(file);
}
// Serve A-Frame library (Bundled)
if (url.pathname === "/aframe.min.js") {
return new Response(aframeMin as any, {
headers: { "Content-Type": "application/javascript" }
});
}
// Serve A-Frame Inspector (Bundled)
if (url.pathname === "/aframe-inspector.min.js") {
return new Response(aframeInspector as any, {
headers: { "Content-Type": "application/javascript" }
});
}
// Handle Save Endpoint
if (req.method === "POST" && url.pathname === "/save") {
console.log("Triggering save...");
try {
// Authentication check (Optional based on AUTH_REQUIRED)
if (SAVE_AUTH_REQUIRED && GIT_AUTH_TOKEN) {
const authHeader = req.headers.get("authorization");
const token = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : null;
if (token !== GIT_AUTH_TOKEN) {
return new Response("Unauthorized", {
status: 401,
headers: { "Access-Control-Allow-Origin": "*" }
});
}
}
const changes = (await req.json()) as Changes;
console.log("Syncing save...");
sync(changes, [examplePath]);
console.log("Synched save.");
// Commit changes to Git
if (GIT_REMOTE_URL && GIT_AUTH_TOKEN) {
const git = simpleGit(PROJECT_DIR);
// Securely provide token via extraHeader to avoid cleartext in URL
await git.addConfig(`http.${GIT_REMOTE_URL}.extraHeader`, `Authorization: Bearer ${GIT_AUTH_TOKEN}`);
await git.add(examplePath);
await git.commit("A-Frame scene update");
await git.push(GIT_REMOTE_URL, "master", { "--set-upstream": null, "--force": true } as any);
}
return new Response("OK", {
status: 200,
headers: { "Access-Control-Allow-Origin": "*" }
});
} catch (e) {
console.error("Error on save:", e);
return new Response("Error on save", { status: 500 });
}
}
// CORS Preflight
if (req.method === "OPTIONS") {
return new Response(null, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
},
});
}
return new Response("Not Found", { status: 404 });
},
};
let server: any;
if (import.meta.main) {
server = Bun.serve(serverOptions);
console.log(`[${projectName}] ready at ${server.url}`);
}