@n3bula/sandbox 0.0.1-alpha.1 → 0.0.1-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -110,7 +110,7 @@ function createSandbox(name, watchFilePath, globals = {}) {
110
110
  });
111
111
  function runCode(code) {
112
112
  return new vm.Script(`(async () => { ${code} })()`).runInContext(sandboxContext, { timeout: 2e3 }).then((res) => res).catch((err) => {
113
- logger.error(err.name, err.message);
113
+ logger.error(err);
114
114
  });
115
115
  }
116
116
  const watcher = new FileWatcher(watchFilePath);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n3bula/sandbox",
3
- "version": "0.0.1-alpha.1",
3
+ "version": "0.0.1-alpha.2",
4
4
  "description": "Simple Sandbox for Node.js module quick test",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",
@@ -9,6 +9,9 @@
9
9
  "sandbox",
10
10
  "node"
11
11
  ],
12
+ "files": [
13
+ "dist"
14
+ ],
12
15
  "contributors": [
13
16
  {
14
17
  "name": "Moriarty47",
package/example/client.ts DELETED
@@ -1 +0,0 @@
1
- console.log(server);
package/example/server.ts DELETED
@@ -1,20 +0,0 @@
1
- import net from 'net';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname, resolve } from 'node:path';
4
-
5
- import { createSandbox } from '../src';
6
-
7
- const PORT = 4000;
8
- const server = net.createServer();
9
- server.listen(PORT, () => console.log(`TCP server listening on ${PORT}`));
10
- const destroy = () => {
11
- server.close();
12
- process.exit();
13
- };
14
- process.on('SIGINT', destroy);
15
- process.on('SIGTERM', destroy);
16
-
17
- const file = resolve(fileURLToPath(dirname(import.meta.url)), './client.ts');
18
- createSandbox('sandbox', file, {
19
- server,
20
- });
@@ -1,90 +0,0 @@
1
- import EventEmitter from 'node:events';
2
- import { FSWatcher, readFile, stat, Stats, watch } from 'node:fs';
3
-
4
- import { logger } from './logger';
5
-
6
- const DEBOUNCE_MS = 200;
7
- const READ_RETRY_MS = 100;
8
- const MAX_READ_RETRIES = 5;
9
-
10
- export class FileWatcher extends EventEmitter {
11
- timer: NodeJS.Timeout | null = null;
12
- lastStat: Stats | null = null;
13
- readRetries = 0;
14
- watcher!: FSWatcher;
15
- constructor(public filePath: string) {
16
- super();
17
- this.scheduleRead = this.scheduleRead.bind(this);
18
- this.startWatch();
19
- }
20
-
21
- safeReadAndNotify() {
22
- readFile(this.filePath, 'utf8', (err, data) => {
23
- if (err) {
24
- if (err.code === 'ENOENT' && this.readRetries < MAX_READ_RETRIES) {
25
- this.readRetries++;
26
- setTimeout(this.safeReadAndNotify, READ_RETRY_MS);
27
- return;
28
- }
29
- logger.error('Read error:', err.code, err.message);
30
- return;
31
- }
32
- this.readRetries = 0;
33
- stat(this.filePath, (err2, fileStat) => {
34
- if (!err2) {
35
- if (this.lastStat && fileStat.mtimeMs === this.lastStat.mtimeMs && fileStat.size === this.lastStat.size)
36
- return;
37
- this.lastStat = fileStat;
38
- }
39
- this.emit(
40
- 'change',
41
- data
42
- .split(/\r?\n/)
43
- .filter(l => !/^\s*\/\//.test(l))
44
- .map(l => l.trim())
45
- .join(' '),
46
- );
47
- });
48
- });
49
- }
50
-
51
- scheduleRead() {
52
- if (this.timer) clearTimeout(this.timer);
53
- this.timer = setTimeout(() => {
54
- this.timer = null;
55
- this.safeReadAndNotify();
56
- }, DEBOUNCE_MS);
57
- }
58
-
59
- startWatch() {
60
- try {
61
- const watcher = watch(this.filePath, { encoding: 'utf8', persistent: true }, this.scheduleRead);
62
-
63
- watcher.on('error', err => {
64
- logger.error('fs.watch error', err);
65
- if (watcher) {
66
- try {
67
- watcher.close();
68
- } catch {}
69
- }
70
- });
71
-
72
- stat(this.filePath, (err, fileStat) => {
73
- if (!err) this.lastStat = fileStat;
74
- });
75
-
76
- logger('Watching', this.filePath);
77
- this.watcher = watcher;
78
- } catch (error: any) {
79
- logger.error('fs.watch error', error.message);
80
- }
81
- }
82
-
83
- destroy() {
84
- if (this.watcher && typeof this.watcher.close === 'function') {
85
- try {
86
- this.watcher.close();
87
- } catch {}
88
- }
89
- }
90
- }
package/src/index.ts DELETED
@@ -1 +0,0 @@
1
- export { createSandbox } from './sandbox';
package/src/logger.ts DELETED
@@ -1,28 +0,0 @@
1
- import { echo } from '@n3bula/echo/node';
2
-
3
- export const createLogger = (tag?: string) => {
4
- const logger = ((...msg: any[]) => {
5
- tag ? echo.fg.cyan(tag, ...msg) : echo.fg.cyan(...msg);
6
- }) as {
7
- (...msg: any[]): void;
8
- info(...msg: any[]): void;
9
- warn(...msg: any[]): void;
10
- error(...msg: any[]): void;
11
- };
12
-
13
- logger.info = (...msg: any[]) => {
14
- tag ? echo.fg('#66b5ff')(tag, ...msg) : echo.fg('#66b5ff')(...msg);
15
- };
16
-
17
- logger.warn = (...msg: any[]) => {
18
- tag ? echo.fg('#ff9966')(tag, ...msg) : echo.fg('#ff9966')(...msg);
19
- };
20
-
21
- logger.error = (...msg: any[]) => {
22
- tag ? echo.fg.orangeRed(tag, ...msg) : echo.fg.orangeRed(...msg);
23
- };
24
-
25
- return logger;
26
- };
27
-
28
- export const logger = createLogger('@n3bula/sandbox');
package/src/sandbox.ts DELETED
@@ -1,46 +0,0 @@
1
- import vm from 'node:vm';
2
-
3
- import { FileWatcher } from './file-watcher';
4
- import { logger } from './logger';
5
-
6
- function createContext(sandboxGlobals = {}) {
7
- const context = vm.createContext({
8
- console,
9
- setTimeout,
10
- setInterval,
11
- clearTimeout,
12
- clearInterval,
13
- fetch: typeof fetch !== 'undefined' ? fetch : undefined,
14
- ...sandboxGlobals,
15
- });
16
- return context;
17
- }
18
-
19
- export function createSandbox(name: string, watchFilePath: string, globals = {}) {
20
- const sandboxContext = createContext({
21
- ...globals,
22
- __sandbox_name: name,
23
- });
24
-
25
- function runCode(code: string) {
26
- const script = new vm.Script(`(async () => { ${code} })()`);
27
- const result: Promise<any> = script.runInContext(sandboxContext, { timeout: 2000 });
28
- return result
29
- .then(res => res)
30
- .catch(err => {
31
- logger.error(err.name, err.message);
32
- });
33
- }
34
-
35
- const watcher = new FileWatcher(watchFilePath);
36
- watcher.on('change', code => {
37
- runCode(code);
38
- });
39
-
40
- const destroy = () => {
41
- watcher.destroy();
42
- process.exit();
43
- };
44
- process.on('SIGINT', destroy);
45
- process.on('SIGTERM', destroy);
46
- }
@@ -1,172 +0,0 @@
1
- import vm from 'node:vm';
2
- import Module from 'node:module';
3
- import { fileURLToPath, pathToFileURL } from 'node:url';
4
- import { dirname, resolve } from 'node:path';
5
- import { existsSync } from 'node:fs';
6
- import { readFile } from 'node:fs/promises';
7
- import { PROTOCOL_FILE, PROTOCOL_NODE, resolvedProtocols } from './utils';
8
-
9
- function createContext(sandboxGlobals = {}) {
10
- const context = vm.createContext({
11
- console,
12
- setTimeout,
13
- setInterval,
14
- clearTimeout,
15
- clearInterval,
16
- fetch: typeof fetch !== 'undefined' ? fetch : undefined,
17
- ...sandboxGlobals,
18
- });
19
- return context;
20
- }
21
-
22
- export function createSandbox(name: string, globals = {}) {
23
- const memoryModules = new Map<string, { code: string; mtime: number }>();
24
-
25
- const moduleInstances = new Map<string, vm.Module>();
26
-
27
- const sandboxContext = createContext({
28
- ...globals,
29
- __sandbox_name: name,
30
- __node_import_fallback: (id: string) => {
31
- try {
32
- return Module.createRequire(import.meta.url)(id);
33
- } catch (error) {
34
- // try without node: prefix
35
- return Module.createRequire(import.meta.url)(id);
36
- }
37
- },
38
- });
39
-
40
- async function resolveSpecifier(specifier: string, referrer?: string) {
41
- const isFileProtocol = !!(referrer && referrer.startsWith(PROTOCOL_FILE));
42
- try {
43
- const url = new URL(specifier, isFileProtocol ? referrer : undefined);
44
- if (resolvedProtocols.includes(url.protocol)) {
45
- return url.toString();
46
- }
47
- } catch (error) {
48
- // not a URL, other resolve solution
49
- }
50
-
51
- if (memoryModules.has(specifier)) return specifier;
52
-
53
- try {
54
- const require = Module.createRequire(isFileProtocol ? referrer : pathToFileURL(`${process.cwd()}/`).toString());
55
- const resolved = require.resolve(specifier);
56
- return pathToFileURL(resolved).toString();
57
- } catch (error) {
58
- // fallback: try resolving as relative to referrer filesystem path
59
- if (isFileProtocol) {
60
- const refPath = fileURLToPath(referrer);
61
- const candidate = resolve(dirname(refPath), specifier);
62
- if (existsSync(candidate)) {
63
- const final = pathToFileURL(candidate).toString();
64
- return final;
65
- }
66
- }
67
- // last resort: return specifier as-is, link may fail
68
- return specifier;
69
- }
70
- }
71
-
72
- async function loadSource(resolved: string) {
73
- const memoryModule = memoryModules.get(resolved);
74
- if (memoryModule) return { source: memoryModule.code, url: resolved };
75
-
76
- if (resolved.startsWith(PROTOCOL_FILE)) {
77
- const filePath = fileURLToPath(resolved);
78
- const code = await readFile(filePath, 'utf8');
79
- return { source: code, url: resolved };
80
- }
81
-
82
- if (resolved.startsWith(PROTOCOL_NODE)) {
83
- const pkg = resolved.slice(PROTOCOL_NODE.length);
84
- const code = `export default globalThis.__node_import_fallback('${pkg}');\nexport const __esModule = true;`;
85
- return { source: code, url: resolved };
86
- }
87
-
88
- try {
89
- const code = await readFile(resolved, 'utf8');
90
- return { source: code, url: resolved };
91
- } catch {
92
- // fallback: create a wrapper that imports via dynamic import
93
- const code = `export default await import(${JSON.stringify(resolved)});\n`;
94
- return { source: code, url: resolved };
95
- }
96
- }
97
-
98
- async function linker(specifier: string, referencingModule: vm.Module) {
99
- const refUrl = (('identifier' in referencingModule && referencingModule.identifier) as string) || undefined;
100
- const resolved = await resolveSpecifier(specifier, refUrl);
101
- const { source, url } = await loadSource(resolved);
102
-
103
- const moduleInstance = moduleInstances.get(url);
104
- if (moduleInstance) return moduleInstance;
105
-
106
- const module = new vm.SourceTextModule(source, {
107
- context: sandboxContext,
108
- identifier: url,
109
- initializeImportMeta: (meta, module) => (meta.url = module.identifier),
110
- });
111
-
112
- moduleInstances.set(url, module);
113
-
114
- // link dependencies recursively inside vm's linker; vm.Module.link willcall our linker for each import
115
- await module.link(linker);
116
- return module;
117
- }
118
-
119
- function registerModule(specifier: string, code: string) {
120
- memoryModules.set(specifier, { code, mtime: Date.now() });
121
- // invalidate instance cache
122
- moduleInstances.delete(specifier);
123
- }
124
-
125
- function unnregisterModule(specifier: string) {
126
- memoryModules.delete(specifier);
127
- moduleInstances.delete(specifier);
128
- }
129
-
130
- async function runModule(
131
- code: string,
132
- specifier: string = `mem://${Date.now()}-${Math.random().toString(36).slice(2)}`,
133
- globals = {},
134
- ) {
135
- Object.assign(sandboxContext, globals);
136
- registerModule(specifier, code);
137
-
138
- const resolved = await resolveSpecifier(specifier);
139
- const { source, url } = await loadSource(resolved);
140
-
141
- const module = new vm.SourceTextModule(source, {
142
- context: sandboxContext,
143
- identifier: url,
144
- initializeImportMeta: (meta, m) => (meta.url = m.identifier),
145
- });
146
-
147
- moduleInstances.set(url, module);
148
-
149
- await module.link(linker);
150
-
151
- const result = await module.evaluate();
152
- return {
153
- module,
154
- namespace: module.namespace,
155
- status: module.status,
156
- evaluationResult: result,
157
- };
158
- }
159
-
160
- function hotReload(specifier: string, newCode: string) {
161
- unnregisterModule(specifier);
162
- registerModule(specifier, newCode);
163
- return runModule(newCode, specifier);
164
- }
165
-
166
- return {
167
- registerModule,
168
- unnregisterModule,
169
- runModule,
170
- hotReload,
171
- };
172
- }
@@ -1,90 +0,0 @@
1
- import net, { Socket } from 'node:net';
2
- import { tmpdir } from 'node:os';
3
- import { join } from 'node:path';
4
- import { IS_WIN } from './utils';
5
- import { chmodSync, existsSync, unlinkSync } from 'node:fs';
6
- import { logger } from './logger';
7
-
8
- function getSocketPath(name: string = 'n3bula-sandbox') {
9
- if (IS_WIN) {
10
- const pipeName = name.replace(/[\\/:\*\?"<>\|]/g, '_');
11
- return `\\\\.\\pipe\\${pipeName}`;
12
- }
13
- return join(tmpdir(), `${name}.sock`);
14
- }
15
-
16
- function cleanupSocketFile(socketPath: string) {
17
- if (IS_WIN) return;
18
- try {
19
- if (existsSync(socketPath)) unlinkSync(socketPath);
20
- } catch {}
21
- }
22
-
23
- export async function createSocketServer(name: string, connectionListener: (socket: Socket) => void) {
24
- const socketPath = getSocketPath(name);
25
- cleanupSocketFile(socketPath);
26
-
27
- const server = net.createServer(socket => {
28
- socket.on('end', () => socket.end());
29
- socket.on('close', () => logger('server closed'));
30
- socket.on('error', err => logger.error('server', err));
31
- connectionListener(socket);
32
- });
33
-
34
- server.listen(socketPath, () => {
35
- logger('Listening on', socketPath);
36
- if (IS_WIN) return;
37
- try {
38
- chmodSync(socketPath, 0o600);
39
- } catch {}
40
- });
41
-
42
- const cleanup = () => {
43
- server.close();
44
- cleanupSocketFile(socketPath);
45
- };
46
- const destroy = () => {
47
- cleanup();
48
- process.exit();
49
- };
50
- process.on('exit', cleanup);
51
- process.on('SIGINT', destroy);
52
- process.on('SIGTERM', destroy);
53
-
54
- return { server, path: socketPath };
55
- }
56
-
57
- function connectSocket(name: string, onConnect?: (socket: Socket) => void) {
58
- const socketPath = getSocketPath(name);
59
- return new Promise<string>((resolve, reject) => {
60
- const client = net.createConnection(socketPath, () => onConnect?.(client));
61
- client.setEncoding('utf8');
62
-
63
- client.on('close', () => logger('client closed'));
64
- client.on('error', err => logger.error('client', err));
65
-
66
- let resp = '';
67
- client.on('data', d => (resp += d));
68
-
69
- client.on('end', () => {
70
- try {
71
- resolve(JSON.parse(resp));
72
- } catch (e) {
73
- reject(e);
74
- }
75
- client.end();
76
- });
77
- });
78
- }
79
-
80
- export function clientSend(name: string, code: string) {
81
- return connectSocket(name, socket => {
82
- socket.write(
83
- `${code
84
- .split(/\r?\n/)
85
- .filter(l => !/^\s*\/\//.test(l))
86
- .map(l => l.trim())
87
- .join(' ')}\n`,
88
- );
89
- });
90
- }
@@ -1,4 +0,0 @@
1
- export const PROTOCOL_FILE = 'file:';
2
- export const PROTOCOL_NODE = 'node:';
3
- export const resolvedProtocols = [PROTOCOL_NODE, PROTOCOL_FILE, 'data:', 'http:', 'https:'];
4
- export const IS_WIN = process.platform === 'win32';
package/tsconfig.json DELETED
@@ -1,21 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "rootDir": ".",
4
- "target": "ES2022",
5
- "lib": ["ES2022"],
6
- "module": "es2022",
7
- "types": ["node"],
8
- "skipLibCheck": true,
9
- "moduleResolution": "bundler",
10
- "noEmit": true,
11
- "esModuleInterop": true,
12
- /* Linting */
13
- "strict": true,
14
- "noUnusedLocals": true,
15
- "noUnusedParameters": true,
16
- "erasableSyntaxOnly": false,
17
- "noFallthroughCasesInSwitch": true,
18
- "noUncheckedSideEffectImports": true
19
- },
20
- "include": ["tsdown.config.ts", "src", "example"]
21
- }
package/tsdown.config.ts DELETED
@@ -1,5 +0,0 @@
1
- import { defineConfig } from 'tsdown';
2
-
3
- export default defineConfig({
4
- entry: ['./src/index.ts'],
5
- });