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

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/README.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # `@n3bula/sandbox`
2
2
 
3
3
  ### Simple Sandbox for Node.js module quick test
4
+
4
5
  Just use for debug
5
6
  Debug the current process without restart process
6
7
 
@@ -18,14 +19,18 @@ pnpm add @n3bula/sandbox
18
19
 
19
20
  ```ts
20
21
  // server.ts
21
- import net from 'net';
22
- import { fileURLToPath } from 'node:url';
22
+ import net from 'node:net';
23
23
  import { dirname, resolve } from 'node:path';
24
+ import { fileURLToPath } from 'node:url';
25
+
24
26
  import { createSandbox } from '@n3bula/sandbox';
27
+
25
28
  const PORT = 4000;
26
29
  const server = net.createServer();
30
+
31
+ export type Server = typeof server;
32
+
27
33
  server.listen(PORT, () => console.log(`TCP server listening on ${PORT}`));
28
- server.on('error', err => console.error('server error', err));
29
34
  const destroy = () => {
30
35
  server.close();
31
36
  process.exit();
@@ -33,13 +38,36 @@ const destroy = () => {
33
38
  process.on('SIGINT', destroy);
34
39
  process.on('SIGTERM', destroy);
35
40
 
36
- createSandbox('sandbox', resolve(fileURLToPath(dirname(import.meta.url)), './client.ts'), { server });
41
+ const file = resolve(fileURLToPath(dirname(import.meta.url)), './client.ts');
42
+ createSandbox(
43
+ file,
44
+ {
45
+ server,
46
+ },
47
+ {
48
+ // name: 'sandbox',
49
+ },
50
+ );
37
51
  ```
38
52
 
39
53
  ```ts
40
54
  // client.ts
41
- console.log(1); // change to console.log(server);
55
+ import type { Server } from './server';
56
+
57
+ declare const server: Server;
58
+ console.log(server, typeof server);
42
59
  // will print current server instance without restart server
60
+
61
+ const fs = _require(
62
+ 'node:fs/promises',
63
+ ) as typeof import('node:fs/promises');
64
+
65
+ const file = await fs.readFile('./example/client.ts', 'utf8');
66
+ console.log('file :>>', file);
67
+
68
+ const { echo } = _require('@n3bula/echo') as typeof import('@n3bula/echo');
69
+
70
+ echo(globalThis);
43
71
  ```
44
72
 
45
73
  ## Author
package/dist/index.d.mts CHANGED
@@ -1,4 +1,10 @@
1
+ import { TsconfigRaw } from "esbuild";
2
+
1
3
  //#region src/sandbox.d.ts
2
- declare function createSandbox(name: string, watchFilePath: string, globals?: {}): void;
4
+ type SandboxOptions = {
5
+ name?: string;
6
+ tsconfig?: string | TsconfigRaw;
7
+ };
8
+ declare function createSandbox(watchFilePath: string, globals?: {}, options?: SandboxOptions): void;
3
9
  //#endregion
4
10
  export { createSandbox };
package/dist/index.mjs CHANGED
@@ -1,6 +1,10 @@
1
+ import { createRequire } from "node:module";
2
+ import { randomUUID } from "node:crypto";
1
3
  import vm from "node:vm";
2
4
  import EventEmitter from "node:events";
3
- import { readFile, stat, watch } from "node:fs";
5
+ import { existsSync, readFileSync, stat, watch } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { buildSync, transformSync } from "esbuild";
4
8
  import { echo } from "@n3bula/echo/node";
5
9
  //#region src/logger.ts
6
10
  const createLogger = (tag) => {
@@ -24,19 +28,47 @@ const logger = createLogger("@n3bula/sandbox");
24
28
  const DEBOUNCE_MS = 200;
25
29
  const READ_RETRY_MS = 100;
26
30
  const MAX_READ_RETRIES = 5;
31
+ const DEFAULT_TSCONFIG = { compilerOptions: {
32
+ strict: false,
33
+ target: "ES2022"
34
+ } };
35
+ function findTsconfigFromProcessRoot() {
36
+ const tsconfigPath = join(process.cwd(), "tsconfig.json");
37
+ if (existsSync(tsconfigPath)) try {
38
+ return JSON.parse(readFileSync(tsconfigPath, "utf8"));
39
+ } catch {
40
+ return;
41
+ }
42
+ }
27
43
  var FileWatcher = class extends EventEmitter {
28
44
  timer = null;
29
45
  lastStat = null;
30
46
  readRetries = 0;
31
47
  watcher;
32
- constructor(filePath) {
48
+ tsOptions;
49
+ constructor(filePath, tsconfig) {
33
50
  super();
34
51
  this.filePath = filePath;
52
+ this.tsconfig = tsconfig;
53
+ this.normalizeTsOptions();
35
54
  this.scheduleRead = this.scheduleRead.bind(this);
36
55
  this.startWatch();
37
56
  }
57
+ normalizeTsOptions() {
58
+ const tsconfig = findTsconfigFromProcessRoot();
59
+ if (tsconfig) {
60
+ this.tsOptions = { tsconfigRaw: tsconfig };
61
+ return;
62
+ }
63
+ if (typeof this.tsconfig === "string") try {
64
+ this.tsOptions = { tsconfigRaw: JSON.parse(this.tsconfig) };
65
+ } catch {
66
+ this.tsOptions = { tsconfig: this.tsconfig };
67
+ }
68
+ else this.tsOptions = { tsconfigRaw: DEFAULT_TSCONFIG };
69
+ }
38
70
  safeReadAndNotify() {
39
- readFile(this.filePath, "utf8", (err, data) => {
71
+ stat(this.filePath, (err, fileStat) => {
40
72
  if (err) {
41
73
  if (err.code === "ENOENT" && this.readRetries < MAX_READ_RETRIES) {
42
74
  this.readRetries++;
@@ -47,13 +79,21 @@ var FileWatcher = class extends EventEmitter {
47
79
  return;
48
80
  }
49
81
  this.readRetries = 0;
50
- stat(this.filePath, (err2, fileStat) => {
51
- if (!err2) {
52
- if (this.lastStat && fileStat.mtimeMs === this.lastStat.mtimeMs && fileStat.size === this.lastStat.size) return;
53
- this.lastStat = fileStat;
54
- }
55
- this.emit("change", data.split(/\r?\n/).filter((l) => !/^\s*\/\//.test(l)).map((l) => l.trim()).join(" "));
56
- });
82
+ if (this.lastStat && fileStat.mtimeMs === this.lastStat.mtimeMs && fileStat.size === this.lastStat.size) return;
83
+ this.lastStat = fileStat;
84
+ const data = buildSync({
85
+ charset: "utf8",
86
+ entryPoints: [this.filePath],
87
+ format: "esm",
88
+ legalComments: "none",
89
+ minify: true,
90
+ minifyIdentifiers: false,
91
+ minifySyntax: false,
92
+ platform: "node",
93
+ write: false,
94
+ ...this.tsOptions
95
+ }).outputFiles[0].contents;
96
+ this.emit("change", transformSync(data, {}).code);
57
97
  });
58
98
  }
59
99
  scheduleRead() {
@@ -91,29 +131,53 @@ var FileWatcher = class extends EventEmitter {
91
131
  }
92
132
  };
93
133
  //#endregion
134
+ //#region src/require.ts
135
+ const requireCache = /* @__PURE__ */ new Map();
136
+ const _require = new Proxy(createRequire(import.meta.url), { apply(target, thisArg, argArray) {
137
+ const [id] = argArray;
138
+ const module = Reflect.apply(target, thisArg, argArray);
139
+ requireCache.set(_require.resolve(id), module);
140
+ return module;
141
+ } });
142
+ function sandboxRequireCleanup() {
143
+ requireCache.forEach((_, id) => {
144
+ if (!_require.cache[id]) return;
145
+ Reflect.deleteProperty(_require.cache, id);
146
+ });
147
+ requireCache.clear();
148
+ }
149
+ //#endregion
94
150
  //#region src/sandbox.ts
95
151
  function createContext(sandboxGlobals = {}) {
96
152
  return vm.createContext({
97
- console,
98
- setTimeout,
99
- setInterval,
100
- clearTimeout,
153
+ _require,
101
154
  clearInterval,
155
+ clearTimeout,
156
+ console,
102
157
  fetch: typeof fetch !== "undefined" ? fetch : void 0,
158
+ setInterval,
159
+ setTimeout,
103
160
  ...sandboxGlobals
104
161
  });
105
162
  }
106
- function createSandbox(name, watchFilePath, globals = {}) {
163
+ function createSandbox(watchFilePath, globals = {}, options = {}) {
107
164
  const sandboxContext = createContext({
108
165
  ...globals,
109
- __sandbox_name: name
166
+ __sandbox_name: options.name || randomUUID()
110
167
  });
111
168
  function runCode(code) {
112
- return new vm.Script(`(async () => { ${code} })()`).runInContext(sandboxContext, { timeout: 2e3 }).then((res) => res).catch((err) => {
169
+ return new Promise((resolve, reject) => {
170
+ try {
171
+ resolve(new vm.Script(`(async () => { ${code} })()`).runInContext(sandboxContext, { timeout: 2e3 }));
172
+ sandboxRequireCleanup();
173
+ } catch (error) {
174
+ reject(error);
175
+ }
176
+ }).then((res) => res).catch((err) => {
113
177
  logger.error(err);
114
178
  });
115
179
  }
116
- const watcher = new FileWatcher(watchFilePath);
180
+ const watcher = new FileWatcher(watchFilePath, options.tsconfig);
117
181
  watcher.on("change", (code) => {
118
182
  runCode(code);
119
183
  });
@@ -0,0 +1,2 @@
1
+ declare const __sandbox_name: string;
2
+ declare const _require: NodeJS.Require;
package/package.json CHANGED
@@ -1,14 +1,25 @@
1
1
  {
2
2
  "name": "@n3bula/sandbox",
3
- "version": "0.0.1-alpha.2",
3
+ "version": "0.0.1-alpha.3",
4
4
  "description": "Simple Sandbox for Node.js module quick test",
5
5
  "type": "module",
6
- "main": "dist/index.mjs",
7
- "typings": "dist/index.d.mts",
8
6
  "keywords": [
9
7
  "sandbox",
10
8
  "node"
11
9
  ],
10
+ "main": "./dist/index.mjs",
11
+ "types": "./dist/index.d.mts",
12
+ "exports": {
13
+ ".": {
14
+ "import": {
15
+ "types": "./dist/index.d.mts",
16
+ "default": "./dist/index.mjs"
17
+ }
18
+ },
19
+ "./types": {
20
+ "types": "./dist/types.d.ts"
21
+ }
22
+ },
12
23
  "files": [
13
24
  "dist"
14
25
  ],
@@ -38,10 +49,12 @@
38
49
  "tsdown": "^0.21.5"
39
50
  },
40
51
  "dependencies": {
52
+ "esbuild": "^0.25.12",
41
53
  "@n3bula/echo": "^0.1.0-alpha.4"
42
54
  },
55
+ "sideEffects": false,
43
56
  "scripts": {
44
- "dev": "tsx --experimental-vm-modules example/server.ts",
57
+ "dev": "pnpm -C=example dev",
45
58
  "build": "tsdown"
46
59
  }
47
60
  }