run-kit 0.7.1

Universal multi-language runner and smart REPL
Documentation
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
use std::fs;
use std::io::{ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Instant;

use anyhow::{Context, Result, bail};
use tempfile::{NamedTempFile, TempDir};

use super::{
    ExecutionOutcome, ExecutionPayload, LanguageEngine, LanguageSession, run_version_command,
};

pub struct TypeScriptEngine {
    executable: PathBuf,
}

impl Default for TypeScriptEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl TypeScriptEngine {
    pub fn new() -> Self {
        let executable = resolve_deno_binary();
        Self { executable }
    }

    fn binary(&self) -> &Path {
        &self.executable
    }

    fn run_command(&self) -> Command {
        Command::new(self.binary())
    }
}

impl LanguageEngine for TypeScriptEngine {
    fn id(&self) -> &'static str {
        "typescript"
    }

    fn display_name(&self) -> &'static str {
        "TypeScript"
    }

    fn aliases(&self) -> &[&'static str] {
        &["ts", "deno"]
    }

    fn supports_sessions(&self) -> bool {
        true
    }

    fn validate(&self) -> Result<()> {
        let mut cmd = self.run_command();
        cmd.arg("--version")
            .stdout(Stdio::null())
            .stderr(Stdio::null());
        let status = handle_deno_io(
            cmd.status(),
            self.binary(),
            "invoke Deno to check its version",
        )?;

        if status.success() {
            Ok(())
        } else {
            bail!("{} is not executable", self.binary().display());
        }
    }

    fn toolchain_version(&self) -> Result<Option<String>> {
        let mut cmd = self.run_command();
        cmd.arg("--version");
        let context = format!("{}", self.binary().display());
        run_version_command(cmd, &context)
    }

    fn execute(&self, payload: &ExecutionPayload) -> Result<ExecutionOutcome> {
        let start = Instant::now();
        let args = payload.args();
        let output = match payload {
            ExecutionPayload::Inline { code, .. } => {
                let mut script =
                    NamedTempFile::new().context("failed to create temporary TypeScript file")?;
                script.write_all(code.as_bytes())?;
                if !code.ends_with('\n') {
                    script.write_all(b"\n")?;
                }
                script.flush()?;

                let mut cmd = self.run_command();
                cmd.arg("run")
                    .args(["--quiet", "--no-check", "--ext", "ts"])
                    .arg(script.path())
                    .args(args)
                    .env("NO_COLOR", "1");
                cmd.stdin(Stdio::inherit());
                handle_deno_io(cmd.output(), self.binary(), "run Deno for inline execution")?
            }
            ExecutionPayload::File { path, .. } => {
                let mut cmd = self.run_command();
                cmd.arg("run")
                    .args(["--quiet", "--no-check", "--ext", "ts"])
                    .arg(path)
                    .args(args)
                    .env("NO_COLOR", "1");
                cmd.stdin(Stdio::inherit());
                handle_deno_io(cmd.output(), self.binary(), "run Deno for file execution")?
            }
            ExecutionPayload::Stdin { code, .. } => {
                let mut cmd = self.run_command();
                cmd.arg("run")
                    .args(["--quiet", "--no-check", "--ext", "ts", "-"])
                    .args(args)
                    .stdin(Stdio::piped())
                    .stdout(Stdio::piped())
                    .stderr(Stdio::piped())
                    .env("NO_COLOR", "1");

                let mut child =
                    handle_deno_io(cmd.spawn(), self.binary(), "start Deno for stdin execution")?;

                if let Some(mut stdin) = child.stdin.take() {
                    stdin.write_all(code.as_bytes())?;
                    if !code.ends_with('\n') {
                        stdin.write_all(b"\n")?;
                    }
                    stdin.flush()?;
                }

                handle_deno_io(
                    child.wait_with_output(),
                    self.binary(),
                    "read output from Deno stdin execution",
                )?
            }
        };

        Ok(ExecutionOutcome {
            language: self.id().to_string(),
            exit_code: output.status.code(),
            stdout: strip_ansi_codes(&String::from_utf8_lossy(&output.stdout)).replace('\r', ""),
            stderr: strip_ansi_codes(&String::from_utf8_lossy(&output.stderr)).replace('\r', ""),
            duration: start.elapsed(),
        })
    }

    fn start_session(&self) -> Result<Box<dyn LanguageSession>> {
        self.validate()?;
        let session = TypeScriptSession::new(self.binary().to_path_buf())?;
        Ok(Box::new(session))
    }
}

fn resolve_deno_binary() -> PathBuf {
    which::which("deno").unwrap_or_else(|_| PathBuf::from("deno"))
}

fn strip_ansi_codes(text: &str) -> String {
    let mut result = String::with_capacity(text.len());
    let mut chars = text.chars();

    while let Some(ch) = chars.next() {
        if ch == '\x1b' {
            if chars.next() == Some('[') {
                for c in chars.by_ref() {
                    if c.is_ascii_alphabetic() {
                        break;
                    }
                }
            }
        } else {
            result.push(ch);
        }
    }

    result
}

fn handle_deno_io<T>(result: std::io::Result<T>, binary: &Path, action: &str) -> Result<T> {
    match result {
        Ok(value) => Ok(value),
        Err(err) if err.kind() == ErrorKind::NotFound => bail!(
            "failed to {} because '{}' was not found in PATH. Install Deno from https://deno.land/manual/getting_started/installation or ensure the binary is available on your PATH.",
            action,
            binary.display()
        ),
        Err(err) => {
            Err(err).with_context(|| format!("failed to {} using {}", action, binary.display()))
        }
    }
}

struct TypeScriptSession {
    deno_path: PathBuf,
    _workspace: TempDir,
    entrypoint: PathBuf,
    snippets: Vec<String>,
    last_stdout: String,
    last_stderr: String,
}

impl TypeScriptSession {
    fn new(deno_path: PathBuf) -> Result<Self> {
        let workspace = TempDir::new().context("failed to create TypeScript session workspace")?;
        let entrypoint = workspace.path().join("session.ts");
        let session = Self {
            deno_path,
            _workspace: workspace,
            entrypoint,
            snippets: Vec::new(),
            last_stdout: String::new(),
            last_stderr: String::new(),
        };
        session.persist_source()?;
        Ok(session)
    }

    fn language_id(&self) -> &str {
        "typescript"
    }

    fn persist_source(&self) -> Result<()> {
        let source = self.render_source();
        fs::write(&self.entrypoint, source)
            .with_context(|| "failed to write TypeScript session source".to_string())
    }

    fn render_source(&self) -> String {
        let mut source = String::from(
            r#"const __print = (value: unknown): void => {
    if (typeof value === "string") {
        console.log(value);
        return;
    }
    try {
        const serialized = JSON.stringify(value, null, 2);
        if (serialized !== undefined) {
            console.log(serialized);
            return;
        }
    } catch (_) {
    }
    console.log(String(value));
};

"#,
        );

        for snippet in &self.snippets {
            source.push_str(snippet);
            if !snippet.ends_with('\n') {
                source.push('\n');
            }
        }

        source
    }

    fn compile_and_run(&self) -> Result<std::process::Output> {
        let mut cmd = Command::new(&self.deno_path);
        cmd.arg("run")
            .args(["--quiet", "--no-check", "--ext", "ts"])
            .arg(&self.entrypoint)
            .env("NO_COLOR", "1");
        handle_deno_io(
            cmd.output(),
            &self.deno_path,
            "run Deno for the TypeScript session",
        )
    }

    fn normalize(text: &str) -> String {
        strip_ansi_codes(&text.replace("\r\n", "\n").replace('\r', ""))
    }

    fn diff_outputs(previous: &str, current: &str) -> String {
        if let Some(suffix) = current.strip_prefix(previous) {
            suffix.to_string()
        } else {
            current.to_string()
        }
    }

    fn run_snippet(&mut self, snippet: String) -> Result<(ExecutionOutcome, bool)> {
        let start = Instant::now();
        self.snippets.push(snippet);
        self.persist_source()?;
        let output = self.compile_and_run()?;

        let stdout_full = Self::normalize(&String::from_utf8_lossy(&output.stdout));
        let stderr_full = Self::normalize(&String::from_utf8_lossy(&output.stderr));

        let stdout = Self::diff_outputs(&self.last_stdout, &stdout_full);
        let stderr = Self::diff_outputs(&self.last_stderr, &stderr_full);
        let success = output.status.success();

        if success {
            self.last_stdout = stdout_full;
            self.last_stderr = stderr_full;
        } else {
            self.snippets.pop();
            self.persist_source()?;
        }

        let outcome = ExecutionOutcome {
            language: self.language_id().to_string(),
            exit_code: output.status.code(),
            stdout,
            stderr,
            duration: start.elapsed(),
        };

        Ok((outcome, success))
    }
}

impl LanguageSession for TypeScriptSession {
    fn language_id(&self) -> &str {
        TypeScriptSession::language_id(self)
    }

    fn eval(&mut self, code: &str) -> Result<ExecutionOutcome> {
        let trimmed = code.trim();
        if trimmed.is_empty() {
            return Ok(ExecutionOutcome {
                language: self.language_id().to_string(),
                exit_code: None,
                stdout: String::new(),
                stderr: String::new(),
                duration: Instant::now().elapsed(),
            });
        }

        if should_treat_as_expression(trimmed) {
            let snippet = wrap_expression(trimmed);
            let (outcome, success) = self.run_snippet(snippet)?;
            if success {
                return Ok(outcome);
            }
        }

        let snippet = prepare_statement(code);
        let (outcome, _) = self.run_snippet(snippet)?;
        Ok(outcome)
    }

    fn shutdown(&mut self) -> Result<()> {
        Ok(())
    }
}

fn wrap_expression(code: &str) -> String {
    let expr = code.trim().trim_end_matches(';').trim_end();
    format!("__print(await ({}));\n", expr)
}

fn prepare_statement(code: &str) -> String {
    let mut snippet = code.to_string();
    if !snippet.ends_with('\n') {
        snippet.push('\n');
    }
    snippet
}

fn should_treat_as_expression(code: &str) -> bool {
    let trimmed = code.trim();
    if trimmed.is_empty() {
        return false;
    }
    if trimmed.contains('\n') {
        return false;
    }

    let trimmed = trimmed.trim_end();
    let without_trailing_semicolon = trimmed.strip_suffix(';').unwrap_or(trimmed).trim_end();
    if without_trailing_semicolon.is_empty() {
        return false;
    }
    if without_trailing_semicolon.contains(';') {
        return false;
    }

    const KEYWORDS: [&str; 11] = [
        "const ",
        "let ",
        "var ",
        "function ",
        "class ",
        "interface ",
        "type ",
        "import ",
        "export ",
        "if ",
        "while ",
    ];
    if KEYWORDS.iter().any(|kw| {
        without_trailing_semicolon.starts_with(kw)
            || without_trailing_semicolon.starts_with(&kw.to_ascii_uppercase())
    }) {
        return false;
    }
    if without_trailing_semicolon.starts_with("return ")
        || without_trailing_semicolon.starts_with("throw ")
    {
        return false;
    }
    true
}