-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathapi.ts
More file actions
370 lines (308 loc) · 9.03 KB
/
api.ts
File metadata and controls
370 lines (308 loc) · 9.03 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
import { ensureFile, walk } from "@std/fs";
import { basename, join, SEPARATOR } from "@std/path";
import type { StatusResult } from "simple-git";
import { createReadWriteLock, type RwLock } from "../../daemon/async.ts";
import { Hono } from "../../runtime/deps.ts";
import { git, lockerGitAPI } from "../git.ts";
import { VERBOSE } from "../main.ts";
import { inferBlockType } from "../meta.ts";
import { broadcast } from "../sse/channel.ts";
import {
applyPatch,
type FSEvent,
type Metadata,
type Patch,
type UpdateResponse,
} from "./common.ts";
import { grep, type GrepResult } from "./grep.ts";
const inferMetadata = async (filepath: string): Promise<Metadata | null> => {
return { kind: "file" };
try {
console.log("filepath", filepath)
const { __resolveType, name, path } = JSON.parse(
await Deno.readTextFile(filepath),
);
console.log("__resolveType", __resolveType)
console.log("name", name)
console.log("path", path)
const blockType = await inferBlockType(__resolveType);
console.log("blockType", blockType)
if (!blockType) {
return { kind: "file" };
}
if (blockType === "pages") {
return {
kind: "block",
name: name,
path: path,
blockType,
__resolveType,
};
}
return {
kind: "block",
blockType,
__resolveType,
};
} catch (error) {
console.log("error", error)
if (error instanceof Deno.errors.NotFound) {
return null;
}
return { kind: "file" };
}
};
const mtimeFor = async (filepath: string) => {
try {
const stats = await Deno.stat(filepath);
return stats.mtime?.getTime() ?? Date.now();
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
return Date.now();
}
throw error;
}
};
const onNotFound = <T>(fallback: T) => (error: unknown) => {
if (error instanceof Deno.errors.NotFound) {
return fallback;
}
throw error;
};
export interface ListAPI {
response: {
metas: Array<{
filepath: string;
metadata: Metadata;
timestamp: number;
}>;
status: StatusResult;
};
}
export interface ReadAPI {
response: {
content: string;
metadata: Metadata;
timestamp: number;
};
}
export interface PatchAPI {
response: UpdateResponse;
body: { patch: Patch; timestamp: number };
}
export interface DeleteAPI {
response: UpdateResponse;
}
export interface GrepAPI {
response: GrepResult;
}
const shouldIgnore = (path: string) => {
if (basename(path) === ".gitignore") {
return false;
}
// Check if path contains these directories anywhere in the path
const ignoredDirs = [
'.git',
'node_modules',
'.next',
'.faststore',
'dist',
'build',
'.turbo'
];
const pathSegments = path.split(SEPARATOR);
return ignoredDirs.some(dir => pathSegments.includes(dir));
};
const systemPathFromBrowser = (pathAndQuery: string) => {
const [url] = pathAndQuery.split("?");
const [_, ...segments] = url.split("/file");
const s = segments.join("/file");
return join(Deno.cwd(), "/", s);
};
const browserPathFromSystem = (filepath: string) =>
filepath.replace(Deno.cwd(), "").replaceAll(SEPARATOR, "/");
export async function* start(since: number): AsyncIterableIterator<FSEvent> {
try {
// Handle invalid since values (NaN, undefined, etc.)
const sinceTimestamp = Number.isFinite(since) ? since : 0;
console.log("[watchFS.start] Starting file walk, since:", since, "-> normalized:", sinceTimestamp);
const walker = walk(Deno.cwd(), { includeDirs: false, includeFiles: true });
let fileCount = 0;
let skippedCount = 0;
let processedCount = 0;
for await (const entry of walker) {
processedCount++;
if (shouldIgnore(entry.path)) {
skippedCount++;
continue;
}
console.log("entry", entry)
const [metadata, mtime] = await Promise.all([
inferMetadata(entry.path),
mtimeFor(entry.path),
]);
console.log("metadata", metadata);
console.log("mtime", mtime)
if (!metadata) {
continue;
}
if (mtime < sinceTimestamp) {
continue;
}
const filepath = browserPathFromSystem(entry.path);
fileCount++;
if (fileCount % 100 === 0) {
console.log(`[watchFS.start] Progress: ${fileCount} files sent, ${processedCount} processed, ${skippedCount} skipped`);
}
yield {
type: "fs-sync",
detail: { metadata, filepath, timestamp: mtime },
};
}
console.log(`[watchFS.start] File walk complete! Processed: ${processedCount}, Sent: ${fileCount}, Skipped: ${skippedCount}`);
console.log("[watchFS.start] Sending fs-snapshot event...");
yield {
type: "fs-snapshot",
detail: { timestamp: Date.now(), status: await git.status() },
};
console.log("[watchFS.start] ✅ fs-snapshot event sent successfully");
} catch (error) {
console.error("[watchFS.start] ❌ Error during file walk:", error);
}
}
export const watchFS = async () => {
const watcher = Deno.watchFs(Deno.cwd(), { recursive: true });
for await (const { kind, paths } of watcher) {
if (kind !== "create" && kind !== "remove" && kind !== "modify") {
continue;
}
const [filepath] = paths;
if (shouldIgnore(filepath)) {
continue;
}
if (VERBOSE) {
console.log("file has changed", kind, paths);
}
const [status, metadata, mtime] = await Promise.all([
git.status(),
inferMetadata(filepath),
mtimeFor(filepath),
]);
broadcast({
type: "fs-sync",
detail: {
status,
metadata,
timestamp: mtime,
filepath: browserPathFromSystem(filepath),
},
});
}
};
export const createFSAPIs = () => {
const app = new Hono();
const lockByPath = new Map<string, RwLock>();
const getRwLock = (filepath: string) => {
if (!lockByPath.has(filepath)) {
lockByPath.set(filepath, createReadWriteLock());
}
return lockByPath.get(filepath);
};
app.use(lockerGitAPI.rlock);
app.get("/file/*", async (c) => {
const filepath = systemPathFromBrowser(c.req.raw.url);
using _ = await getRwLock(filepath)?.rlock();
try {
const [
metadata,
content,
stats,
] = await Promise.all([
inferMetadata(filepath),
Deno.readTextFile(filepath),
Deno.stat(filepath),
]);
const timestamp = stats.mtime?.getTime() ?? Date.now();
return c.json({ content, metadata, timestamp });
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
c.status(404);
return c.json({ timestamp: Date.now() });
}
throw error;
}
});
app.patch("/file/*", async (c) => {
const filepath = systemPathFromBrowser(c.req.raw.url);
const {
patch,
timestamp: mtimeClient,
} = await c.req.json<PatchAPI["body"]>();
using _ = await getRwLock(filepath)?.wlock();
const [mtimeBefore, content] = await Promise.all([
mtimeFor(filepath),
Deno.readTextFile(filepath).catch(onNotFound(null)),
]);
const result = applyPatch(content, patch);
if (!result.conflict && result.content) {
await ensureFile(filepath);
await Deno.writeTextFile(filepath, result.content);
}
const [status, metadata, mtimeAfter] = await Promise.all([
git.status(),
inferMetadata(filepath),
mtimeFor(filepath),
]);
const update: UpdateResponse = result.conflict
? { conflict: true, status, metadata, timestamp: mtimeAfter, content }
: {
conflict: false,
status,
metadata,
timestamp: mtimeAfter,
content: mtimeBefore !== mtimeClient ? result.content : undefined,
};
return c.json(update);
});
app.delete("/file/*", async (c) => {
const filepath = systemPathFromBrowser(c.req.raw.url);
using _ = await getRwLock(filepath)?.wlock();
await Deno.remove(filepath);
const update: UpdateResponse = {
conflict: false,
status: await git.status(),
metadata: null,
timestamp: Date.now(),
content: undefined,
};
return c.json(update);
});
app.get("/grep", async (c) => {
const query = c.req.query("query");
const includePattern = c.req.query("includePattern") || "*";
const excludePattern = c.req.query("excludePattern");
const caseInsensitive = c.req.query("caseInsensitive") === "true";
const isRegex = c.req.query("isRegex") === "true";
const limit = parseInt(c.req.query("limit") || "100");
const filepath = c.req.query("filepath");
if (!query) {
c.status(400);
return c.json({ error: "Query parameter 'query' is required" });
}
try {
const options = {
caseInsensitive,
isRegex,
includePattern,
excludePattern,
limit,
filepath,
};
const result = await grep(query, options);
return c.json(result);
} catch (_error) {
return c.json({ error: "Internal server error during grep operation" });
}
});
return app;
};