@n3bula/sandbox 0.0.1-alpha.1 → 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) => {
113
- logger.error(err.name, err.message);
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) => {
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,28 @@
1
1
  {
2
2
  "name": "@n3bula/sandbox",
3
- "version": "0.0.1-alpha.1",
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
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
12
26
  "contributors": [
13
27
  {
14
28
  "name": "Moriarty47",
@@ -35,10 +49,12 @@
35
49
  "tsdown": "^0.21.5"
36
50
  },
37
51
  "dependencies": {
52
+ "esbuild": "^0.25.12",
38
53
  "@n3bula/echo": "^0.1.0-alpha.4"
39
54
  },
55
+ "sideEffects": false,
40
56
  "scripts": {
41
- "dev": "tsx --experimental-vm-modules example/server.ts",
57
+ "dev": "pnpm -C=example dev",
42
58
  "build": "tsdown"
43
59
  }
44
60
  }
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
- });