File size: 1,132 Bytes
f816273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { mkdtemp, writeFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { spawn } from 'node:child_process'

const scriptUrl = process.env.SCRIPT_URL

if (!scriptUrl) {
  console.error('SCRIPT_URL environment variable is required.')
  process.exit(1)
}

const directory = await mkdtemp(join(tmpdir(), 'remote-script-'))
const scriptPath = join(directory, 'index.js')

try {
  const response = await fetch(scriptUrl)
  if (!response.ok) throw new Error(`Download failed: ${response.status} ${response.statusText}`)
  await writeFile(scriptPath, Buffer.from(await response.arrayBuffer()), { mode: 0o700 })

  const child = spawn(process.execPath, [scriptPath], { stdio: 'inherit', env: process.env })
  child.on('error', (error) => {
    console.error(error)
    process.exitCode = 1
  })
  child.on('exit', (code, signal) => {
    if (signal) process.kill(process.pid, signal)
    else process.exitCode = code ?? 1
  })
} catch (error) {
  console.error(error)
  process.exitCode = 1
} finally {
  process.on('exit', () => rm(directory, { recursive: true, force: true }))
}