-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtrpc.ts
More file actions
512 lines (431 loc) · 13.7 KB
/
Copy pathtrpc.ts
File metadata and controls
512 lines (431 loc) · 13.7 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
import { initTRPC } from "@trpc/server";
import superjson from "superjson";
import { z } from "zod";
import fetch from "node-fetch";
import fsPromises from "fs/promises";
import fs from "fs";
import path from "path";
import { observable } from "@trpc/server/observable";
import { openInExplorer } from "./open-folder";
import { openFile } from "./open-file";
import { getSampleHooks } from "./get-sample-hooks";
import { HOOK_PATH } from "./constants";
import { configValidator, updateConfig } from "./update-config";
import { substituteTemplate } from "./templateSubstitution";
import { getFullPath, getRoute } from "./utils/get-full-path";
export type { ConfigValidatorType } from "./update-config";
type ExtendedConfigValidatorType = ConfigValidatorType & {
method: "POST" | "GET" | "PUT" | "DELETE" | "PATCH";
};
import logger from "@captain/logger";
import type { LogLevels } from "@captain/logger";
import type { ConfigValidatorType } from "./update-config";
export const t = initTRPC.create({
transformer: superjson,
});
export const cliApiRouter = t.router({
onLog: t.procedure.subscription(() => {
return observable<{ message: string; level: LogLevels; ts: number }>(
(emit) => {
const onLog = (m: {
message: string;
level: LogLevels;
ts: number;
}) => {
emit.next(m);
};
logger.subscribe(onLog);
return () => {
logger.unsubscribe(onLog);
};
}
);
}),
getBlobs: t.procedure
.input(
z.object({
path: z.array(z.string()),
})
)
.query(async ({ input }) => {
const fullPath = getFullPath(input.path);
logger.debug(`Getting blobs from ${fullPath}`);
if (!fs.existsSync(fullPath)) {
// TODO: this should probably be an error, and the frontend should handle it
return [];
}
const hooks = await fsPromises.readdir(fullPath);
const res = hooks
.filter(
(hookFile) =>
hookFile.includes(".json") && !hookFile.includes(".config.json")
)
.map(async (hook) => {
const bodyPromise = fsPromises.readFile(
path.join(fullPath, hook),
"utf-8"
);
const configPath = hook.replace(".json", "") + ".config.json";
let config;
if (fs.existsSync(path.join(fullPath, configPath))) {
config = await fsPromises.readFile(
path.join(fullPath, configPath),
"utf-8"
);
}
return {
name: hook,
body: await bodyPromise,
config: config // TODO: validate config
? (JSON.parse(config) as ConfigValidatorType)
: undefined,
};
});
return Promise.all(res);
}),
getFilesAndFolders: t.procedure
.input(
z.object({
path: z.array(z.string()),
})
)
.query(({ input }) => {
const fullPath = getFullPath(input.path);
const dirListing: { folders: string[]; files: string[] } = {
folders: [],
files: [],
};
if (!fs.existsSync(fullPath)) {
logger.warn(`Path ${fullPath} does not exist`);
return dirListing;
}
fs.readdirSync(fullPath).forEach((file) => {
if (fs.lstatSync(`${fullPath}/${file}`).isDirectory()) {
dirListing.folders.push(file);
} else {
if (file.startsWith(".")) return; // skip hidden files
dirListing.files.push(file);
}
});
return dirListing;
}),
openFolder: t.procedure
.input(z.object({ path: z.string() }))
.mutation(async ({ input }) => {
// if running in codespace, early return
// eslint-disable-next-line turbo/no-undeclared-env-vars
if (process.env.CODESPACES) {
throw new Error(
"Sorry, opening folders in codespaces is not supported yet."
);
}
// if running over ssh, early return
if (
// eslint-disable-next-line turbo/no-undeclared-env-vars
process.env.SSH_CONNECTION ||
// eslint-disable-next-line turbo/no-undeclared-env-vars
process.env.SSH_CLIENT ||
// eslint-disable-next-line turbo/no-undeclared-env-vars
process.env.SSH_TTY
) {
throw new Error(
"Sorry, opening folders on remote connections is not supported yet."
);
}
try {
await openInExplorer(path.join(HOOK_PATH, input.path));
} catch (e) {
logger.error(
"Failed to open folder (unless you're on Windows, then this just happens)",
e
);
}
}),
openFile: t.procedure
.input(z.object({ path: z.string() }))
.mutation(async ({ input }) => {
// if running in codespace, early return
// eslint-disable-next-line turbo/no-undeclared-env-vars
if (process.env.CODESPACES) {
throw new Error(
"Sorry, opening files in codespaces is not supported yet."
);
}
// if running over ssh, early return
if (
// eslint-disable-next-line turbo/no-undeclared-env-vars
process.env.SSH_CONNECTION ||
// eslint-disable-next-line turbo/no-undeclared-env-vars
process.env.SSH_CLIENT ||
// eslint-disable-next-line turbo/no-undeclared-env-vars
process.env.SSH_TTY
) {
throw new Error(
"Sorry, opening files on remote connections is not supported yet."
);
}
try {
await openFile(path.join(HOOK_PATH, input.path));
} catch (e) {
logger.error(
"Failed to open file (unless you're on Windows, then this just happens)",
e
);
}
}),
getSampleHooks: t.procedure.mutation(async () => {
await getSampleHooks();
}),
runFile: t.procedure
.input(
z.object({
file: z.string(),
})
)
.mutation(async ({ input }) => {
const { file } = input;
let hasCustomConfig = false;
logger.info(`Reading file ${file}`);
let config = {
url: "",
query: undefined,
headers: {
"Content-Type": "application/json",
},
method: "POST",
} as ExtendedConfigValidatorType;
const fileName = file.replace(".json", "");
const configName = `${fileName}.config.json`;
if (fs.existsSync(path.join(HOOK_PATH, configName))) {
hasCustomConfig = true;
logger.info(`Found ${configName}, reading it`);
const configFileContents = await fsPromises
.readFile(path.join(HOOK_PATH, configName))
.then(
(x) =>
// TODO: validate config
JSON.parse(x.toString()) as ExtendedConfigValidatorType
);
config = {
...config,
...configFileContents,
};
// template substitution for header values
if (config.headers) {
config.headers = Object.fromEntries(
Object.entries(config.headers).map(([key, value]) => {
return [key, substituteTemplate({ template: value })];
})
);
}
}
const data = await fsPromises.readFile(path.join(HOOK_PATH, file));
if (!config.url) {
logger.error(
`Missing URL, please add it to the configuration for this hook`
);
throw new Error(
`Missing URL, please add it to the configuration for this hook`
);
}
try {
logger.info(
`Sending to ${config.url} ${
hasCustomConfig ? `with custom config from ${configName}` : ""
}\n`
);
const fetchedResult = await fetch(config.url, {
method: config.method,
headers: config.headers,
body: config.method !== "GET" ? data.toString() : undefined,
}).then((res) => res.json());
logger.info(
`Got response: \n\n${JSON.stringify(fetchedResult, null, 2)}\n`
);
return fetchedResult;
} catch (e) {
if ((e as { code: string }).code === "ECONNREFUSED") {
logger.error("Connection refused. Is the server running?");
} else {
logger.error(e);
}
throw e;
}
}),
createHook: t.procedure
.input(
z.object({
name: z.string(),
body: z.string(),
config: configValidator.optional(),
path: z.array(z.string()).optional(),
})
)
.mutation(async ({ input }) => {
const { name, body, config } = input;
const fullPath = getFullPath(input.path);
logger.info(`Creating ${name}.json`);
await fsPromises.writeFile(path.join(fullPath, `${name}.json`), body);
if (config?.url || config?.query || config?.headers) {
logger.info(`Config specified, creating ${name}.config.json`);
return await updateConfig({ name, config });
}
}),
updateHook: t.procedure
.input(
z.object({
name: z.string(),
body: z.string(),
config: configValidator.optional(),
path: z.array(z.string()).optional(),
})
)
.mutation(async ({ input }) => {
const { body, config } = input;
const fullPath = getFullPath(input.path);
const name = input.name.split(".json")[0];
if (!name) throw new Error("No name");
const bodyPath = path.join(fullPath, `${name}.json`);
logger.info(`Updating ${bodyPath}`);
const existingBody = await fsPromises.readFile(bodyPath, "utf-8");
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const updatedBody = {
...JSON.parse(existingBody),
...JSON.parse(body),
};
await fsPromises.writeFile(
bodyPath,
JSON.stringify(updatedBody, null, 2)
);
if (
config?.url ||
config?.query ||
config?.headers ||
fs.existsSync(path.join(fullPath, `${name}.config.json`))
) {
logger.info(`Config specified, updating ${name}.config.json`);
return await updateConfig({ name, config, path: fullPath });
}
}),
createFolder: t.procedure
.input(
z.object({
name: z.string(),
path: z.array(z.string()).optional(),
})
)
.mutation(({ input }) => {
const pathArr = input.path ? [...input.path, input.name] : [input.name];
const fullPath = getFullPath(pathArr);
const route = getRoute(pathArr);
logger.info(`Creating new folder: ${fullPath}`);
fs.mkdirSync(fullPath);
return {
route: `/${route}/`,
};
}),
createFile: t.procedure
.input(
z.object({
name: z.string(),
path: z.array(z.string()).optional(),
})
)
.mutation(({ input }) => {
const pathArr = input.path
? [...input.path, `${input.name}.json`]
: [`${input.name}.json`];
const fullPath = getFullPath(pathArr);
const route = getRoute(pathArr);
logger.info(`Creating new file: ${fullPath}`);
fs.writeFileSync(fullPath, "{}");
return {
route: `/${route}`,
};
}),
parseUrl: t.procedure
.input(
z.object({
url: z.string(),
})
)
.query(async ({ input }) => {
const { url } = input;
const fullPath = path.join(
HOOK_PATH,
...url.split("/").map((x) => decodeURI(x))
);
if (!fs.existsSync(fullPath)) {
const d = {
type: "notFound",
path: decodeURI(url),
data: {},
} as const;
return d;
}
if (url.endsWith(".json")) {
const configPath = fullPath.replace(".json", "") + ".config.json";
const bodyPromise = fsPromises.readFile(fullPath, "utf-8");
const configPromise = fsPromises
.readFile(configPath, "utf-8")
// TODO: validate config
.then((x) => JSON.parse(x) as ConfigValidatorType)
.catch(() => undefined);
const hookData = {
name: fullPath.split("/").pop(),
body: await bodyPromise,
config: await configPromise,
} as const;
const d = {
type: "file" as const,
path: decodeURI(url),
data: hookData,
} as const;
return d;
} else {
// get folders and files in folder
const dirListing: {
folders: string[];
files: {
name: string;
body: string;
config: ConfigValidatorType | undefined;
}[];
} = {
folders: [],
files: [],
};
const listingPromises = fs
.readdirSync(fullPath)
.map(async (maybeFile) => {
if (fs.lstatSync(`${fullPath}/${maybeFile}`).isDirectory()) {
dirListing.folders.push(maybeFile);
} else {
if (maybeFile.startsWith(".")) return; // skip hidden files
if (maybeFile.endsWith(".config.json")) return; // skip config files
const filePath = path.join(fullPath, maybeFile);
const configPath = filePath.replace(".json", "") + ".config.json";
const bodyPromise = fsPromises.readFile(filePath, "utf-8");
const configPromise = fsPromises
.readFile(configPath, "utf-8")
.then((x) => JSON.parse(x) as ConfigValidatorType)
.catch(() => undefined);
dirListing.files.push({
name: maybeFile,
body: await bodyPromise,
config: await configPromise,
});
}
});
await Promise.allSettled(listingPromises);
const d = {
type: "folder" as const,
path: decodeURI(url),
data: dirListing,
} as const;
return d;
}
}),
});
// export type definition of API
export type CliApiRouter = typeof cliApiRouter;