Skip to content

Commit c4eac46

Browse files
authored
Merge pull request #40 from Kikobeats/next
chore: add allow
2 parents 796f50d + 775e3f5 commit c4eac46

2 files changed

Lines changed: 66 additions & 3 deletions

File tree

src/index.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,14 @@ const [nodeMajor] = process.version.slice(1).split('.').map(Number)
1919

2020
const PERMISSION_FLAG = nodeMajor >= 24 ? '--permission' : '--experimental-permission'
2121

22-
const flags = ({ memory }) => {
22+
const flags = ({ memory, allow }) => {
2323
const flags = ['--disable-warning=ExperimentalWarning', PERMISSION_FLAG]
2424
if (memory) flags.push(`--max-old-space-size=${memory}`)
25+
allow.forEach(resource => flags.push(`--allow-${resource}`))
2526
return flags.join(' ')
2627
}
2728

28-
module.exports = (snippet, { tmpdir, timeout, memory, throwError = true } = {}) => {
29+
module.exports = (snippet, { tmpdir, timeout, memory, throwError = true, allow = [] } = {}) => {
2930
if (!['function', 'string'].includes(typeof snippet)) throw new TypeError('Expected a function')
3031
const compilePromise = compile(snippet, tmpdir)
3132

@@ -38,7 +39,7 @@ module.exports = (snippet, { tmpdir, timeout, memory, throwError = true } = {})
3839
const subprocess = $('node', ['-', JSON.stringify(args)], {
3940
env: {
4041
...process.env,
41-
NODE_OPTIONS: flags({ memory })
42+
NODE_OPTIONS: flags({ memory, allow })
4243
},
4344
timeout,
4445
killSignal: 'SIGKILL'

test/allow.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
'use strict'
2+
3+
const test = require('ava')
4+
5+
const isolatedFunction = require('..')
6+
7+
const [nodeMajor] = process.version.slice(1).split('.').map(Number)
8+
9+
test('child-process', async t => {
10+
const [fn, cleanup] = isolatedFunction(
11+
() => {
12+
const { execSync } = require('child_process')
13+
return execSync('echo hello').toString()
14+
},
15+
{
16+
allow: ['child_process']
17+
}
18+
)
19+
20+
t.teardown(cleanup)
21+
22+
const { value } = await fn()
23+
t.is(value, 'hello\n')
24+
})
25+
;(nodeMajor >= 25 ? test : test.skip)('network', async t => {
26+
const [fn, cleanup] = isolatedFunction(
27+
async () => {
28+
function doFetch (url) {
29+
return new Promise((resolve, reject) => {
30+
const req = require('node:http').get(url, res => {
31+
let data = ''
32+
33+
res.on('data', chunk => {
34+
data += chunk
35+
})
36+
37+
res.on('end', () => {
38+
resolve({
39+
statusCode: res.statusCode,
40+
headers: res.headers,
41+
body: data
42+
})
43+
})
44+
})
45+
46+
req.on('error', reject)
47+
})
48+
}
49+
50+
const { statusCode } = await doFetch('http://example.com')
51+
return statusCode
52+
},
53+
{
54+
allow: ['net']
55+
}
56+
)
57+
58+
t.teardown(cleanup)
59+
60+
const { value } = await fn()
61+
t.is(value, 200)
62+
})

0 commit comments

Comments
 (0)