# All files / src/lib pyodide-runner.ts

9.7% Statements 23/237
100% Branches 0/0
0% Functions 0/6
9.7% Lines 23/237

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    2381x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x

    1x
    1x

    1x
    1x

     type PyodideInterface = Record<string, unknown> // Avoid importing pyodide at type-check time

    let pyodideInstance: PyodideInterface | null = null
    let pyodideLoading: Promise<PyodideInterface> | null = null
    let initializationError: Error | null = null

    export async function getPyodide(): Promise<PyodideInterface> {
      // If we had an initialization error, throw it
      if (initializationError) {
        throw initializationError
      }

      if (pyodideInstance) {
        return pyodideInstance
      }

      if (pyodideLoading) {
        return pyodideLoading
      }

      try {
        const { loadPyodide } = await import('pyodide')

        pyodideLoading = loadPyodide({
          indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.27.0/full/',
        }).then((pyodide) => {
          pyodideInstance = pyodide
          initializationError = null
          return pyodide
        }).catch((err) => {
          initializationError = err instanceof Error ? err : new Error(String(err))
          pyodideLoading = null
          throw initializationError
        })

        return pyodideLoading
      } catch (err) {
        initializationError = err instanceof Error ? err : new Error(String(err))
        pyodideLoading = null
        throw initializationError
      }
    }

    export async function runPythonCode(code: string): Promise<{ output?: string; error?: string }> {
      try {
        const pyodide = await getPyodide()

        // Reset stdout/stderr for each run
        pyodide.runPython(`
    import sys
    from io import StringIO
    sys.stdout = StringIO()
    sys.stderr = StringIO()
    `)

        try {
          const result = await pyodide.runPythonAsync(code)

          // Flush and collect stdout/stderr after async execution
          const stdout = pyodide.runPython('sys.stdout.getvalue()')
          const stderr = pyodide.runPython('sys.stderr.getvalue()')

          let output = stdout || ''
          if (stderr) {
            output += (output ? '\n' : '') + stderr
          }
          if (result !== undefined && result !== null && String(result) !== 'None') {
            output += (output ? '\n' : '') + String(result)
          }

          return { output: output || '(no output)' }
        } catch (runErr) {
          // Get any stderr output that might have been captured
          let stderr = ''
          try {
            stderr = pyodide.runPython('sys.stderr.getvalue()')
          } catch {
            // Ignore errors getting stderr
          }

          const errorMessage = runErr instanceof Error ? runErr.message : String(runErr)
          return {
            output: '',
            error: stderr ? `${stderr}\n${errorMessage}` : errorMessage
          }
        }
      } catch (err) {
        return {
          output: '',
          error: `Python environment error: ${err instanceof Error ? err.message : String(err)}`
        }
      }
    }

    export interface InteractiveCallbacks {
      onOutput?: (text: string) => void
      onError?: (text: string) => void
      onInputRequest?: (prompt: string) => Promise<string>
    }

    export async function runPythonCodeInteractive(
      code: string,
      callbacks: InteractiveCallbacks
    ): Promise<void> {
      const pyodide = await getPyodide()

      // Set up interactive stdout/stderr handlers
      pyodide.runPython(`
    import sys
    from io import StringIO

    class InteractiveStdout:
        def __init__(self, callback):
            self.callback = callback
            self.buffer = ""

        def write(self, text):
            self.buffer += text
            if "\\n" in text:
                lines = self.buffer.split("\\n")
                for line in lines[:-1]:
                    if line:
                        self.callback(line)
                self.buffer = lines[-1]
            return len(text)

        def flush(self):
            if self.buffer:
                self.callback(self.buffer)
                self.buffer = ""

    class InteractiveStderr:
        def __init__(self, callback):
            self.callback = callback
            self.buffer = ""

        def write(self, text):
            self.buffer += text
            if "\\n" in text:
                lines = self.buffer.split("\\n")
                for line in lines[:-1]:
                    if line:
                        self.callback(line)
                self.buffer = lines[-1]
            return len(text)

        def flush(self):
            if self.buffer:
                self.callback(self.buffer)
                self.buffer = ""
    `)

      const outputCallback = (text: string) => {
        if (callbacks.onOutput) {
          callbacks.onOutput(text)
        }
      }

      const errorCallback = (text: string) => {
        if (callbacks.onError) {
          callbacks.onError(text)
        }
      }

      pyodide.globals.set('__output_callback__', outputCallback)
      pyodide.globals.set('__error_callback__', errorCallback)

      pyodide.runPython(`
    sys.stdout = InteractiveStdout(__output_callback__)
    sys.stderr = InteractiveStderr(__error_callback__)
    `)

      const customInput = async (prompt = '') => {
        if (callbacks.onInputRequest) {
          const value = await callbacks.onInputRequest(prompt)
          return value
        }
        return ''
      }

      pyodide.globals.set('js_input_handler', customInput)

      // Set up custom input function using asyncio.run() which is the modern approach
      await pyodide.runPythonAsync(`
    import builtins
    from pyodide.ffi import to_js
    import asyncio

    async def async_input(prompt=""):
        import sys
        sys.stdout.write(prompt)
        sys.stdout.flush()
        result = await js_input_handler(prompt)
        return result

    def custom_input(prompt=""):
        import asyncio
        try:
            # Try to get the running loop (works in async context)
            loop = asyncio.get_running_loop()
            # If we're in an async context, we need to use a different approach
            import pyodide.webloop
            future = asyncio.ensure_future(async_input(prompt))
            return pyodide.webloop.WebLoop().run_until_complete(future)
        except RuntimeError:
            # No running loop, create a new one
            return asyncio.run(async_input(prompt))

    builtins.input = custom_input
    `)

      try {
        await pyodide.runPythonAsync(code)

        pyodide.runPython('sys.stdout.flush()')
        pyodide.runPython('sys.stderr.flush()')
      } catch (err) {
        if (callbacks.onError) {
          callbacks.onError(err instanceof Error ? err.message : String(err))
        }
        throw err
      }
    }

    export function isPyodideReady(): boolean {
      return pyodideInstance !== null
    }

    export function getPyodideError(): Error | null {
      return initializationError
    }

    export function resetPyodide(): void {
      pyodideInstance = null
      pyodideLoading = null
      initializationError = null
    }