-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
436 lines (404 loc) · 19.7 KB
/
Copy pathindex.ts
File metadata and controls
436 lines (404 loc) · 19.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
#!/usr/bin/env node
const version = require("./package.json").version;
const fs = require("fs");
const access = require("fs/promises").access;
const readline = require("readline");
const nodeFetch = require("node-fetch");
const child_process = require("child_process");
const websocket = require('ws').WebSocket;
const fileHeader = `/// <reference types="@pylonbot/runtime" />
/// <reference types="@pylonbot/runtime-discord" />
// This states that you are writing code using Pylon types, do not remove it if you want to your code to work!\n`;
let [, , ...args] = process.argv;
for (let i = 0; i < args.length; i++) {
args[i].trim();
}
if (
args[0] == "help" ||
args[0] == "-h" ||
args[0] == "--help" ||
args.length == 0
) {
if (args[1] == "help" || args[1] == "-h" || args[1] == "--help") {
console.log("It's a help command. Is that really so hard to figure out?");
} else {
console.log(`
Pylon CLI v${version}
pylon help - Displays this message
pylon <command> help - Displays more information about a command
pylon init - Locally creates a new project, grabs the code from your Pylon online editor, \x1b[1musing
this command will overwrite your locally saved code permanently, so be careful!\x1b[0m
pylon publish - Publishes all of your scripts to the Pylon editor, \x1b[1musing
this command will overwrite your Pylon editor code permanently, so be careful!\x1b[0m
pylon pull - Pulls the code of your project from the Pylon editor, \x1b[1musing
this command will overwrite your locally saved code permanently, so be careful!\x1b[0m
pylon version - Displays Pylon CLI current version
`);
}
} else if (args[0] == "init" || args[0] == "i") {
if (args[1] == "help" || args[1] == "-h" || args[1] == "--help") {
console.log(
`\`pylon init\` - Initiates a new Pylon project locally. You will need to have added Pylon to your server to start using it here.`
);
} else {
console.log('\x1b[34mInitiating new project...\x1b[0m');
try {
child_process.execSync(`npm i --save-dev typescript tslib @rollup/plugin-typescript https://gitpkg.now.sh/pylonbot/pylon-sdk-types/runtime https://gitpkg.now.sh/pylonbot/pylon-sdk-types/runtime-discord`);
child_process.execSync(`npm i -g rollup`);
} catch(e) {
console.log(e);
process.exit();
} finally {
console.log('\x1b[32m✔️ Installed dependencies: rollup, typescript, tslib, @rollup/plugin-typescript, @pylonbot/runtime, @pylonbot/runtime-discord\x1b[0m')
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
console.log(
'This bit\'s kinda weird. Login to https://pylon.bot, open Developer Tools > Storage > Local Storage > https://pylon.bot. \nYou should see a table with a part that says "token". The string next to this is your authentication token.'
);
rl.question("Pylon API token: ", function (token) {
console.log(
"\nOpen the script editor of the guild that you'd like to connect to. At this URL, you should see something like `/deployments/123456789/editor`. \nThis long number is your deployment ID."
);
rl.question("Deployment ID: ", async function (deployment_id) {
// fetch current script
let response = await nodeFetch(
`https://pylon.bot/api/deployments/${deployment_id}`,
{
method: "GET",
headers: {
Authorization: token,
},
}
);
if (!response.ok) {
console.log(
"Hmm, something went wrong. Probably either your Pylon API token or deployment ID was incorrect."
);
process.exit();
}
let editorData = await response.json();
console.log(
`\n\x1b[34mFound deployment to guild '${editorData.guild.name}'\x1b[0m`
);
const gitignoreContent = `# Be careful with this: removing the line that ignores the config.json could lead to your Pylon token being exposed if you ever intend to put this project on GitHub.
config.json
bundle.ts
rollup.config.js`;
fs.writeFileSync(`.gitignore`, gitignoreContent, "utf8");
const configContent = `{
"token": "${token}",
"deployment_id": "${deployment_id}"
}`;
fs.writeFile(`config.json`, configContent, "utf8", () => { });
const rollupConfigContent = `import typescript from '@rollup/plugin-typescript';
export default {
input: 'src/main.ts',
output: {
file: 'bundle.ts',
format: 'cjs'
},
plugins: [typescript({target: "es2017"})]
};`;
fs.writeFile(`rollup.config.js`, rollupConfigContent, "utf8", () => { });
fs.mkdir(`src/`, () => { });
console.log(`\x1b[32m➕ Created default folders and files\x1b[0m`);
// fetch current script
async function pull() {
function betterRmdir(path) {
if (fs.existsSync(path)) {
fs.readdirSync(path).forEach(function (file, index) {
var curPath = path + "/" + file;
if (fs.lstatSync(curPath).isDirectory()) {
// recurse
betterRmdir(curPath);
} else {
// delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
}
let project = JSON.parse(editorData.script.project);
let files = project.files;
// remove source folder
betterRmdir(`src/`);
// reimport source folder
await fs.mkdir(`src/`, () => { });
for (let i = 0; i < files.length; i++) {
let paths = files[i].path.split("/");
function previousPaths(index) {
let previousPaths = "";
for (let a = 1; a < index; a++) {
previousPaths = `${previousPaths}/${paths[a]}`;
}
return previousPaths;
}
for (let e = 0; e < paths.length; e++) {
// if it is a file path
if (e == paths.length - 1) {
let content = files[i].content;
if (paths[e].endsWith(".ts")) {
content = `${fileHeader}${files[i].content}`;
}
if (files[i].path.endsWith(`${paths[e]}/`)) {
await fs.mkdir(
`src${previousPaths(e)}/${paths[e]}`,
() => { }
);
} else {
await fs.writeFile(
`src${previousPaths(e)}/${paths[e]}`,
content,
"utf8",
() => { }
);
}
} else {
await fs.mkdir(
`src/${previousPaths(e)}/${paths[e]}/`,
() => { }
);
}
}
}
console.log(
`\x1b[32m✔️ Successfully pulled ${files.length} item(s)\x1b[0m`
);
console.log(`\x1b[32m✔️ Published to '${editorData.guild.name}'!\x1b[0m`);
const ws = new websocket(editorData.workbench_url);
console.log(`\x1b[32m🛠️ Connected to workbench.\x1b[0m`)
console.log(`\x1b[2m(Kill connection with CTRL + C)\x1b[0m`)
ws.on('message', function message(data) {
data = JSON.parse(data.toString());
let logContent = data[0].data[0];
if (data[0].method == "error") {
logContent = '\x1b[31m' + logContent + '\x1b[0m';
}
console.log(logContent);
});
}
pull();
rl.close();
});
});
}
} else if (args[0] == "publish" || args[0] == "p") {
if (args[1] == "help" || args[1] == "-h" || args[1] == "--help") {
console.log(
`\`pylon publish\` - Publishes your local code to the Pylon editor and bot. You will need to have added Pylon to your server, and to have run the \`pylon init\` command to start using it.`
);
} else {
try {
fs.accessSync(`${process.cwd()}/config.json`);
} catch {
console.log(`\x1b[31mError: config.json file not found. Run \`pylon init\` before using this command.\x1b[0m`);
process.exit();
}
const config = require(`${process.cwd()}/config.json`);
console.log(`\x1b[34mBundling project...\x1b[0m`);
child_process.exec(
`rollup -c "rollup.config.js" --configPlugin typescript --no-strict`,
async (err, stdout, sterr) => {
if (err) {
console.log(err);
process.exit();
}
console.log(`\x1b[32m📦 Successfully bundled.\x1b[0m`);
await fs.readFile(`bundle.ts`, "utf8", async (err, data) => {
if (err) {
console.log(err);
process.exit();
}
if (data.includes(fileHeader)) {
data.replace(fileHeader, "");
}
function getFiles(dir, files_) {
files_ = files_ || [];
var files = fs.readdirSync(dir);
for (var i in files) {
var name = dir + "/" + files[i];
if (fs.statSync(name).isDirectory()) {
getFiles(name, files_);
} else {
files_.push(name);
}
}
return files_;
}
let files = getFiles(`src/`, "");
let bodyFiles = [];
async function loopFiles() {
for (let i = 0; i < files.length; i++) {
let fileData = fs.readFileSync(files[i], "utf8");
if (fileData.includes(fileHeader)) {
fileData = fileData.replace(fileHeader, "");
}
bodyFiles.push({
path: files[i].replace(`src/`, ""),
content: fileData,
});
if (i == files.length - 1) {
publish(bodyFiles);
}
}
}
loopFiles();
async function publish(bodyFiles) {
const reqBody = JSON.stringify({
script: {
contents: data,
project: {
files: bodyFiles,
},
},
});
let response = await nodeFetch(
`https://pylon.bot/api/deployments/${config.deployment_id}`,
{
method: "POST",
headers: {
Authorization: config.token,
},
body: reqBody,
}
);
if (!response.ok) {
console.log(`${response.status}: ${response.statusText}`);
process.exit();
} else {
let json = await response.json();
console.log(`\x1b[32m✔️ Published to '${json.guild.name}'!\x1b[0m`);
const ws = new websocket(json.workbench_url);
console.log(`\x1b[32m🛠️ Connected to workbench.\x1b[0m`)
console.log(`\x1b[2m(Kill connection with CTRL + C)\x1b[0m`)
ws.on('message', function message(data) {
data = JSON.parse(data.toString());
let logContent = data[0].data[0];
if (data[0].method == "error") {
logContent = '\x1b[31m' + logContent + '\x1b[0m';
}
console.log(logContent);
});
}
}
});
}
);
}
} else if (args[0] == "pull") {
if (args[1] == "help" || args[1] == "-h" || args[1] == "--help") {
console.log(
`\`pylon pull\` - Pulls your code from the Pylon editor. You will need to have added Pylon to your server, and to have run the \`pylon init\` command to start using it.`
);
} else {
try {
fs.accessSync(`${process.cwd()}/config.json`);
} catch {
console.log(`\x1b[31mError: config.json file not found. Run \`pylon init\` before using this command.\x1b[0m`);
process.exit();
}
const config = require(`${process.cwd()}/config.json`);
// fetch current script
async function pull() {
let response = await nodeFetch(
`https://pylon.bot/api/deployments/${config.deployment_id}`,
{
method: "GET",
headers: {
Authorization: config.token,
},
}
);
if (!response.ok) {
console.log(
"Hmm, something went wrong. Probably either your Pylon API token or deployment ID was incorrect."
);
process.exit();
}
function betterRmdir(path) {
if (fs.existsSync(path)) {
fs.readdirSync(path).forEach(function (file, index) {
var curPath = path + "/" + file;
if (fs.lstatSync(curPath).isDirectory()) {
// recurse
betterRmdir(curPath);
} else {
// delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
}
let editorData = await response.json();
console.log(
`\n\x1b[34mFound deployment to guild '${editorData.guild.name}'\x1b[0m`
);
let project = JSON.parse(editorData.script.project);
let files = project.files;
// remove source folder
betterRmdir(`src/`);
// reimport source folder
await fs.mkdir(`src/`, () => { });
for (let i = 0; i < files.length; i++) {
let paths = files[i].path.split("/");
function previousPaths(index) {
let previousPaths = "";
for (let a = 1; a < index; a++) {
previousPaths = `${previousPaths}/${paths[a]}`;
}
return previousPaths;
}
for (let e = 0; e < paths.length; e++) {
// if it is a file path
if (e == paths.length - 1) {
let content = files[i].content;
if (paths[e].endsWith(".ts")) {
content = `${fileHeader}${files[i].content}`;
}
if (files[i].path.endsWith(`${paths[e]}/`)) {
await fs.mkdir(`src${previousPaths(e)}/${paths[e]}`, () => { });
} else {
await fs.writeFile(
`src${previousPaths(e)}/${paths[e]}`,
content,
"utf8",
() => { }
);
}
} else {
await fs.mkdir(`src/${previousPaths(e)}/${paths[e]}/`, () => { });
}
}
}
console.log(
`\x1b[32m✔️ Successfully pulled ${files.length} item(s)\x1b[0m`
);
const ws = new websocket(editorData.workbench_url);
console.log(`\x1b[32m🛠️ Connected to workbench.\x1b[0m`)
console.log(`\x1b[2m(Kill connection with CTRL + C)\x1b[0m`)
ws.on('message', function message(data) {
data = JSON.parse(data.toString());
let logContent = data[0].data[0];
if (data[0].method == "error") {
logContent = '\x1b[31m' + logContent + '\x1b[0m';
}
console.log(logContent);
});
}
pull();
}
} else if (args[0] == "version" || args[0] == "-v" || args[0] == "--version") {
if (args[1] == "help" || args[1] == "-h" || args[1] == "--help") {
console.log(`\`pylon version\` - Checks current version of Pylon CLI`);
} else {
const version = require("./package.json").version;
console.log(`v${version}`);
}
} else {
console.log("Command not found. Try `pylon help`");
}