loading
index.js
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
// this is a crazy hack to make crosis work in nodejs. Crosis
// is only intended for use in the browser though this should work.
global.WebSocket = require("ws");

const fetch = require("node-fetch");
const crosis = require("@replit/crosis");

// this is the id of the repl you want to connect to. If you do not
// own the repl some operations are now allowed and changes will not
// persist.
//
// You can get the replid by going to any repl, opening the browser
// console and typing:
// window.store.getState().plugins.infoprovider.state.repl.id
const replID = '8b6f7ee8-4962-4804-be78-e69992ef389a';

// This is the token you received from @turbio.
const apiKey = process.env.API_KEY;

if (!apiKey) {
  console.log('This demo requires an API key!');
  console.log('You can fork it and insert your API key on line 19');
  process.exit(1);
}

async function connect() {
	const client = new crosis.Client();

	const token = await getToken(replID, apiKey);
	await client.connect({ token });

	// To do anything useful you'll need a channel to the service
	// you'd like to use. Here we'll open a channel to an exec service
	// which can run any command inside the repl.
	const ch = client.openChannel({ service: "exec" });

    ch.on("command", command => {
	  switch (command.body) {
		  // the exe service sends many status messages but we only
		  // care about the output from the command.
		  case 'output':
		  	console.log('>', command.output);
			break;
	  }
    });

	// the exec service has a request/response style interface so
	// we can use crosis' `request` to get a promise.
  await ch.request({ exec: { args: ['echo', 'hello world'] } }); 

	client.close();
}

connect();

function getToken(replId, apiKey) {
  return fetch(`https://repl.it/api/v0/repls/${replId}/token`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ apiKey })
  }).then(res => res.json());
}
Fetching token