mock-tls-server 0.0.2 → 1.0.0

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/lib/net.js CHANGED
@@ -1,8 +1,11 @@
1
- import {extendedError, log, normalizeArgs} from './utils.js'
2
- import {EventEmitter} from 'events'
3
- import {MockSocket} from './socket.js'
4
- import {globalKernel} from './kernel.js'
5
- import stream from 'stream'
1
+ import {extendedError, log, normalizeArgs} from './utils.js';
2
+ import {EventEmitter} from 'node:events';
3
+ import {MockSocket} from './socket.js';
4
+ import {globalKernel} from './kernel.js';
5
+
6
+ /**
7
+ * @typedef {import('node:stream').Duplex} DuplexStream
8
+ */
6
9
 
7
10
  /**
8
11
  * @typedef {object} SocketConnectOpts
@@ -10,6 +13,7 @@ import stream from 'stream'
10
13
  * @property {boolean} [allowHalfOpen=false] If set to false, then the
11
14
  * socket will automatically end the writable side when the readable side
12
15
  * ends.
16
+ * @property {SocketCallback} [connectListener]
13
17
  */
14
18
 
15
19
  /**
@@ -19,41 +23,62 @@ import stream from 'stream'
19
23
  * ends.
20
24
  */
21
25
 
26
+ /**
27
+ * @typedef {object} ListenOptions
28
+ * @property {number} port The port to listen on.
29
+ * @property {() => void} listeningListener If it exists, installed as
30
+ * a listener for the 'listening' event.
31
+ */
32
+
33
+ /**
34
+ * @callback PlainCallback
35
+ * @returns {void}
36
+ */
37
+
38
+ /**
39
+ * @callback CountCallback
40
+ * @param {Error} [err] If not null, an error occurred.
41
+ * @param {number} [count] The number of connected clients.
42
+ * @returns {void}
43
+ */
44
+
22
45
  /**
23
46
  * Initiate a connection to a given server port.
24
47
  *
25
- * @param {number|SocketConnectOpts} options The server port to connect to.
26
- * Must already be listening.
48
+ * @param {number |
49
+ * (SocketConnectOpts & import('node:stream').DuplexOptions)} options The
50
+ * server port to connect to. Must already be listening.
27
51
  * @param {SocketCallback} [connectListener] Event listener for the 'connect'
28
52
  * event.
29
- * @returns {stream.Duplex} The client side HalfSocket.
53
+ * @returns {DuplexStream} The client side HalfSocket.
30
54
  * @throws {TypeError} Invalid type for port.
31
55
  */
32
56
  export function connect(options, connectListener) {
33
- const opts = normalizeArgs(options, {connectListener})
34
- const {port, connectListener: listener, ...rest} = opts
57
+ const opts = normalizeArgs(options, {connectListener});
58
+ const {port, connectListener: listener, ...rest} = opts;
35
59
 
36
- if (typeof port !== 'number') {
37
- throw new TypeError('Invalid type for port')
60
+ if (typeof opts.port !== 'number') {
61
+ throw new TypeError('Invalid type for port');
38
62
  }
39
- const ms = new MockSocket(rest)
40
- const srv = /** @type {Server} */ (globalKernel.lookup(port))
63
+
64
+ const ms = new MockSocket(rest);
65
+ const srv = /** @type {Server} */ (globalKernel.lookup(port));
41
66
 
42
67
  if (srv) {
43
- srv._addClient(ms)
68
+ srv._addClient(ms);
44
69
  if (listener) {
45
- ms.clientSocket.on('connect', listener)
70
+ ms.clientSocket.on('connect', listener);
46
71
  }
47
- process.nextTick(() => ms.clientSocket.emit('connect'))
72
+ process.nextTick(() => ms.clientSocket.emit('connect'));
48
73
  } else {
49
74
  const er = extendedError(`Error: connect ECONNREFUSED ${port}`, {
50
75
  code: 'ECONNREFUSED',
51
76
  port,
52
- })
53
- process.nextTick(() => ms.clientSocket.emit('error', er))
77
+ });
78
+ process.nextTick(() => ms.clientSocket.emit('error', er));
54
79
  }
55
80
 
56
- return ms.clientSocket
81
+ return ms.clientSocket;
57
82
  }
58
83
 
59
84
  /**
@@ -63,13 +88,12 @@ export function connect(options, connectListener) {
63
88
  * @returns {Server} The server that was found, or null if none found.
64
89
  */
65
90
  export function getServer(options) {
66
- const opts = normalizeArgs(options)
67
- return /** @type {Server} */ (globalKernel.lookup(opts.port))
91
+ const {port} = normalizeArgs(options);
92
+ return /** @type {Server} */ (globalKernel.lookup(port));
68
93
  }
69
94
 
70
95
  /**
71
- * @callback SocketCallback
72
- * @param {stream.Duplex} socket Server side of socket that was just connected.
96
+ * @typedef {(socket: DuplexStream) => void} SocketCallback
73
97
  */
74
98
 
75
99
  /**
@@ -84,16 +108,16 @@ export class Server extends EventEmitter {
84
108
  * listener for the 'listening' event, if provided.
85
109
  */
86
110
  constructor(options, connectionListener) {
87
- super()
88
- const opts = normalizeArgs(options, {connectionListener})
111
+ super();
112
+ const opts = normalizeArgs(options, {connectionListener});
89
113
 
90
- this.clients = new Set()
91
- this.port = null
92
- this.listening = false
93
- this.closing = false
114
+ this.clients = new Set();
115
+ this.port = null;
116
+ this.listening = false;
117
+ this.closing = false;
94
118
 
95
119
  if (opts.connectionListener) {
96
- this.on('connection', opts.connectionListener)
120
+ this.on('connection', opts.connectionListener);
97
121
  }
98
122
  }
99
123
 
@@ -109,57 +133,50 @@ export class Server extends EventEmitter {
109
133
  emit(eventName, ...args) {
110
134
  log(this.constructor.name, eventName, ...args.map(
111
135
  o => ((typeof o === 'object') ? o.constructor.name || o.toString() : o)
112
- ))
113
- return super.emit(eventName, ...args)
136
+ ));
137
+ return super.emit(eventName, ...args);
114
138
  }
115
139
 
116
140
  address() {
117
- return (this.port === null) ? null : `mock:${this.port}`
141
+ return (this.port === null) ? null : `mock:${this.port}`;
118
142
  }
119
143
 
120
- /**
121
- * @typedef {object} ListenOptions
122
- * @property {number} port The port to listen on.
123
- * @property {Function} listeningListener If it exists, installed as
124
- * a listener for the 'listening' event.
125
- */
126
-
127
144
  /**
128
145
  * Listen for incoming connections. Whenever `connect` is called on this
129
146
  * server's port, create a mock socket wrapped in a TLSSocket.
130
147
  *
131
148
  * @param {number|ListenOptions} [options] Port number or options object.
132
- * @param {Function} [listeningListener] If it exists, installed as
149
+ * @param {() => void} [listeningListener] If it exists, installed as
133
150
  * a listener for the 'listening' event.
134
151
  * @returns {Server} This.
135
152
  */
136
153
  listen(options, listeningListener) {
137
- const opts = normalizeArgs(options, {listeningListener})
154
+ const opts = normalizeArgs(options, {listeningListener});
138
155
 
139
156
  if (this.listening) {
140
157
  const er = extendedError('Server already listening', {
141
158
  code: 'ERR_SERVER_ALREADY_LISTEN',
142
- })
143
- process.nextTick(() => this.emit('error', er))
144
- return this
159
+ });
160
+ process.nextTick(() => this.emit('error', er));
161
+ return this;
145
162
  }
146
163
 
147
164
  try {
148
- this.port = globalKernel.open(opts.port, this)
165
+ this.port = globalKernel.open(opts.port, this);
149
166
  } catch (er) {
150
- process.nextTick(() => this.emit('error', er))
151
- return this
167
+ process.nextTick(() => this.emit('error', er));
168
+ return this;
152
169
  }
153
170
 
154
171
  if (opts.listeningListener) {
155
- this.on('listening', opts.listeningListener)
172
+ this.on('listening', opts.listeningListener);
156
173
  }
157
174
 
158
- this.listening = true
175
+ this.listening = true;
159
176
  process.nextTick(() => {
160
- this.emit('listening')
161
- })
162
- return this
177
+ this.emit('listening');
178
+ });
179
+ return this;
163
180
  }
164
181
 
165
182
  /**
@@ -172,21 +189,21 @@ export class Server extends EventEmitter {
172
189
  */
173
190
  _addClient(ms) {
174
191
  if (!this.listening) {
175
- throw new Error('Server not listening')
192
+ throw new Error('Server not listening');
176
193
  }
177
194
 
178
- this.clients.add(ms)
195
+ this.clients.add(ms);
179
196
  for (const sock of [ms.serverSocket, ms.clientSocket]) {
180
197
  for (const event of ['close', 'error']) {
181
198
  sock.on(event, () => {
182
- this.clients.delete(ms)
183
- this._checkClosed()
184
- })
199
+ this.clients.delete(ms);
200
+ this._checkClosed();
201
+ });
185
202
  }
186
203
  }
187
204
 
188
- this.emit('connection', ms.serverSocket)
189
- return this
205
+ this.emit('connection', ms.serverSocket);
206
+ return this;
190
207
  }
191
208
 
192
209
  /**
@@ -194,16 +211,12 @@ export class Server extends EventEmitter {
194
211
  */
195
212
  _checkClosed() {
196
213
  if (this.closing && (this.clients.size === 0)) {
197
- this.closing = false
198
- this.port = null
199
- process.nextTick(() => this.emit('close'))
214
+ this.closing = false;
215
+ this.port = null;
216
+ process.nextTick(() => this.emit('close'));
200
217
  }
201
218
  }
202
219
 
203
- /**
204
- * @callback PlainCallback
205
- * @returns {void}
206
- */
207
220
  /**
208
221
  * Close down all of the clients, then the server.
209
222
  *
@@ -212,24 +225,17 @@ export class Server extends EventEmitter {
212
225
  */
213
226
  close(cb) {
214
227
  if (cb) {
215
- this.on('close', cb)
228
+ this.on('close', cb);
216
229
  }
217
- this.listening = false
218
- this.closing = true
230
+ this.listening = false;
231
+ this.closing = true;
219
232
  for (const cli of this.clients) {
220
- cli.serverSocket.end()
233
+ cli.serverSocket.end();
221
234
  }
222
- this._checkClosed()
223
- return this
235
+ this._checkClosed();
236
+ return this;
224
237
  }
225
238
 
226
- /**
227
- * @callback CountCallback
228
- * @param {Error} [err] If not null, an error occurred.
229
- * @param {number} [count] The number of connected clients.
230
- * @returns {void}
231
- */
232
-
233
239
  /**
234
240
  * Get the number of current clients.
235
241
  *
@@ -239,16 +245,16 @@ export class Server extends EventEmitter {
239
245
  */
240
246
  getConnections(cb) {
241
247
  if (typeof cb !== 'function') {
242
- throw new TypeError('Callback not a function')
248
+ throw new TypeError('Callback not a function');
243
249
  }
244
250
  process.nextTick(() => {
245
251
  if (this.listening) {
246
- cb(null, this.clients.size)
252
+ cb(undefined, this.clients.size);
247
253
  } else {
248
- cb(new Error('Not listening'))
254
+ cb(new Error('Not listening'));
249
255
  }
250
- })
251
- return this
256
+ });
257
+ return this;
252
258
  }
253
259
  }
254
260
 
@@ -261,7 +267,7 @@ export class Server extends EventEmitter {
261
267
  * @returns {Server} The created Server.
262
268
  */
263
269
  export function createServer(opts, connectionListener) {
264
- return new Server(opts, connectionListener)
270
+ return new Server(opts, connectionListener);
265
271
  }
266
272
 
267
273
  export default {
@@ -269,4 +275,4 @@ export default {
269
275
  createServer,
270
276
  getServer,
271
277
  Server,
272
- }
278
+ };
package/lib/socket.js CHANGED
@@ -1,6 +1,6 @@
1
- import {log} from './utils.js'
2
- import stream from 'stream'
3
- import util from 'util'
1
+ import {log} from './utils.js';
2
+ import stream from 'node:stream';
3
+ import util from 'node:util';
4
4
 
5
5
  // A mock socket is two duplex HalfSockets, each of which is connected to the
6
6
  // other with a crossover cable.
@@ -17,7 +17,7 @@ import util from 'util'
17
17
  * @param {Buffer|string} data The data that was written.
18
18
  * @param {string} encoding The encoding for the data.
19
19
  */
20
- const WRITTEN_EVENT = 'written'
20
+ const WRITTEN_EVENT = 'written';
21
21
 
22
22
  /**
23
23
  * One end of a socket, either client or server. Serves as a pass-through to
@@ -41,9 +41,9 @@ export class HalfSocket extends stream.Duplex {
41
41
  autoDestroy: true,
42
42
  emitClose: true,
43
43
  ...opts,
44
- }
45
- super(opts)
46
- this.name = name
44
+ };
45
+ super(opts);
46
+ this.name = name;
47
47
  }
48
48
 
49
49
  /**
@@ -56,22 +56,32 @@ export class HalfSocket extends stream.Duplex {
56
56
  * otherwise.
57
57
  */
58
58
  emit(eventName, ...args) {
59
- log(this.name, eventName, ...args)
60
- return super.emit(eventName, ...args)
59
+ log(this.name, eventName, ...args);
60
+ return super.emit(eventName, ...args);
61
61
  }
62
62
 
63
+ /**
64
+ * A chunk was written to the stream.
65
+ *
66
+ * @param {any} chunk
67
+ * @param {BufferEncoding} encoding
68
+ * @param {(error?: Error | null) => void} cb
69
+ */
63
70
  _write(chunk, encoding, cb) {
64
71
  // De-couple the halves
65
- this.emit(WRITTEN_EVENT, chunk, encoding)
66
- cb()
72
+ this.emit(WRITTEN_EVENT, chunk, encoding);
73
+ cb();
67
74
  }
68
75
 
76
+ /**
77
+ * @param {number} _sz
78
+ */
69
79
  // eslint-disable-next-line class-methods-use-this, no-empty-function
70
- _read(sz) {
80
+ _read(_sz) {
71
81
  }
72
82
 
73
83
  [util.inspect.custom]() {
74
- return `[HalfSocket "${this.name}"]`
84
+ return `[HalfSocket "${this.name}"]`;
75
85
  }
76
86
  }
77
87
 
@@ -88,28 +98,28 @@ export class MockSocket extends stream.Duplex {
88
98
  * sides.
89
99
  */
90
100
  constructor(opts) {
91
- super(opts)
92
- this.clientSocket = new HalfSocket('cli', opts)
93
- this.serverSocket = new HalfSocket('srv', opts)
101
+ super(opts);
102
+ this.clientSocket = new HalfSocket('cli', opts);
103
+ this.serverSocket = new HalfSocket('srv', opts);
94
104
 
95
105
  // Simulate the TCP flavor of the Internet.
96
106
  // If we were going to add delays, throttling, or Nagel-like coalescing,
97
107
  // this would be the place to do it.
98
- this.clientSocket.on(WRITTEN_EVENT, (chunk, encoding) => {
99
- this.serverSocket.push(chunk)
100
- })
101
- this.serverSocket.on(WRITTEN_EVENT, (chunk, encoding) => {
102
- this.clientSocket.push(chunk)
103
- })
108
+ this.clientSocket.on(WRITTEN_EVENT, (chunk, _encoding) => {
109
+ this.serverSocket.push(chunk);
110
+ });
111
+ this.serverSocket.on(WRITTEN_EVENT, (chunk, _encoding) => {
112
+ this.clientSocket.push(chunk);
113
+ });
104
114
 
105
115
  // This is from the song by Jimmy Buffer:
106
116
  // FINs to the left.
107
117
  this.clientSocket.on('finish', () => {
108
- this.serverSocket.push(null)
109
- })
118
+ this.serverSocket.push(null);
119
+ });
110
120
  // FINs to the right.
111
121
  this.serverSocket.on('finish', () => {
112
- this.clientSocket.push(null)
113
- })
122
+ this.clientSocket.push(null);
123
+ });
114
124
  }
115
125
  }
package/lib/utils.js CHANGED
@@ -1,42 +1,55 @@
1
- import util from 'util'
1
+ import util from 'node:util';
2
+
3
+ /**
4
+ * @template T
5
+ * @typedef {T | Readonly<T[]>} Many
6
+ */
2
7
 
3
- // Object.<> triggers this:
4
- /* eslint-disable jsdoc/check-types */
5
8
  /**
6
9
  * Normalize arguments for functions that take one of these three things
7
10
  * for the first arg: port (number), options (object), listener (function).
8
11
  *
9
- * @param {object|number|Function} [options] Options.
10
- * @param {Object.<string,Function>} [listener] Callback.
11
- * @returns {object} The normalized options.
12
+ * @template {Record<string,Function|undefined>} T
13
+ * @template U
14
+ * @param {number | U} [options] Options.
15
+ * @param {T} [listener] Callback.
16
+ * @returns {U & {port?: number} & T} The normalized options.
12
17
  * @throws {TypeError} No callback allowed for this function.
13
18
  */
14
- export function normalizeArgs(options = {}, listener = null) {
15
- let opts = null
19
+ export function normalizeArgs(
20
+ options,
21
+ listener = undefined
22
+ ) {
23
+ let opts = null;
24
+ if (options === undefined) {
25
+ options = Object.create(null);
26
+ }
16
27
  if (typeof options === 'function') {
17
28
  if (listener) {
18
- listener[Object.keys(listener)[0]] = options
29
+ // @ts-ignore
30
+ listener[Object.keys(listener)[0]] = options;
19
31
  } else {
20
- throw new Error('Function provided for options when not expecting it')
32
+ throw new Error('Function provided for options when not expecting it');
21
33
  }
22
- options = {}
34
+ options = Object.create(null);
23
35
  }
24
36
  switch (typeof options) {
25
37
  case 'object':
26
- opts = options || {}
27
- break
38
+ opts = options || Object.create(null);
39
+ break;
28
40
  case 'number':
29
- opts = {port: options}
30
- break
41
+ opts = {port: options};
42
+ break;
31
43
  default:
32
- throw new TypeError('Invalid type for options')
44
+ throw new TypeError(`Invalid type for options: ${typeof options} (${options})`);
33
45
  }
46
+
47
+ // @ts-ignore
34
48
  return {
35
49
  ...listener,
36
50
  ...opts,
37
- }
51
+ };
38
52
  }
39
- /* eslint-enable jsdoc/check-types*/
40
53
 
41
54
  /**
42
55
  * Create an extended Error, by assigning all of the properties in opts.
@@ -46,46 +59,49 @@ export function normalizeArgs(options = {}, listener = null) {
46
59
  * @returns {Error} The extended error.
47
60
  */
48
61
  export function extendedError(message, opts) {
49
- const er = new Error(message)
50
- Object.assign(er, opts)
51
- return er
62
+ const er = new Error(message);
63
+ Object.assign(er, opts);
64
+ return er;
52
65
  }
53
66
 
54
67
  /**
55
68
  * Select some properties from an object into multiple other objects.
56
69
  *
57
- * @param {object} obj The source object.
58
- * @param {string[][]} args Arrays of strings to select into the result
70
+ * @template {Record<string,any>} T
71
+ * @param {T} obj The source object.
72
+ * @param {(keyof T)[][]} args Arrays of strings to select into the result
59
73
  * objects.
60
- * @returns {object[]} One object for each of args, plus an extra one for
61
- * everything that was left over.
74
+ * @returns {Partial<Record<keyof T, any>>[]} One object for each of args,
75
+ * plus an extra one for everything that was left over.
62
76
  */
63
77
  export function select(obj, ...args) {
64
- const res = args.map(() => ({}))
65
- const leftovers = {}
66
- res.push(leftovers)
78
+ /** @type {Partial<Record<keyof T, any>>[]} */
79
+ const res = args.map(() => Object.create(null));
80
+ const leftovers = Object.create(null);
81
+ res.push(leftovers);
67
82
 
68
83
  if (!obj) {
69
- return res
84
+ return res;
70
85
  }
71
86
 
72
- const sets = args.map(a => new Set(a))
87
+ const sets = args.map(a => new Set(a));
73
88
  for (const [k, v] of Object.entries(obj)) {
74
- let found = false
89
+ let found = false;
75
90
  sets.forEach((s, i) => {
76
91
  if (!found && s.has(k)) {
77
- found = true
78
- res[i][k] = v
92
+ found = true;
93
+ // @ts-ignore
94
+ res[i][k] = v;
79
95
  }
80
- })
96
+ });
81
97
  if (!found) {
82
- leftovers[k] = v
98
+ leftovers[k] = v;
83
99
  }
84
100
  }
85
- return res
101
+ return res;
86
102
  }
87
103
 
88
104
  /** @type {util.DebugLoggerFunction|util.DebugLogger} */
89
105
  export let log = util.debuglog('mock-tls-server', optimized => {
90
- log = optimized
91
- })
106
+ log = optimized;
107
+ });
package/package.json CHANGED
@@ -1,17 +1,16 @@
1
1
  {
2
2
  "name": "mock-tls-server",
3
- "version": "0.0.2",
3
+ "version": "1.0.0",
4
4
  "description": "",
5
5
  "main": "lib/index.js",
6
6
  "type": "module",
7
7
  "types": "types/index.d.ts",
8
8
  "scripts": {
9
- "test": "ava",
10
- "coverage": "c8 --all --src lib -r lcov npm test",
11
- "lint": "eslint . --ext js",
12
- "docs": "jsdoc -c .jsdoc.conf",
9
+ "test": "c8 ava",
10
+ "lint": "eslint .",
11
+ "docs": "typedoc",
13
12
  "types": "tsc",
14
- "check": "npm run lint && npm run types && npm run docs && npm run coverage && npm pack --dry-run"
13
+ "build": "npm run lint && npm run types && npm run docs && npm run test && npm pack --dry-run"
15
14
  },
16
15
  "keywords": [
17
16
  "tls",
@@ -28,24 +27,27 @@
28
27
  ],
29
28
  "author": "Joe Hildebrand <joe-github@cursive.net>",
30
29
  "license": "MIT",
30
+ "repository": "hildjj/mock-tls-server",
31
31
  "dependencies": {
32
- "jsrsasign": "^10.4.1"
32
+ "jsrsasign": "11.1.0"
33
33
  },
34
34
  "devDependencies": {
35
- "@cto.af/eslint-config": "^0.0.10",
36
- "@types/node": "^16.10.3",
37
- "ava": "^3.15.0",
38
- "c8": "^7.10.0",
39
- "eslint": "^7.32.0",
40
- "eslint-plugin-ava": "^13.0.0",
41
- "eslint-plugin-jsdoc": "^36.1.1",
42
- "eslint-plugin-node": "^11.1.0",
43
- "jsdoc": "^3.6.7",
44
- "minami": "^1.2.3",
45
- "p-event": "^4.2.0",
46
- "typescript": "^4.4.3"
35
+ "@cto.af/eslint-config": "4.1.6",
36
+ "@types/jsrsasign": "10.5.14",
37
+ "@types/node": "22.5.2",
38
+ "ava": "6.1.3",
39
+ "c8": "10.1.2",
40
+ "eslint": "9.9.1",
41
+ "eslint-plugin-ava": "^15.0.1",
42
+ "eslint-plugin-jsdoc": "50.2.2",
43
+ "eslint-plugin-markdown": "5.1.0",
44
+ "eslint-plugin-node": "11.1.0",
45
+ "p-event": "6.0.1",
46
+ "typedoc": "0.26.6",
47
+ "typescript": "^5.5.4"
47
48
  },
49
+ "packageManager": "pnpm@9.9.0",
48
50
  "engines": {
49
- "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
51
+ "node": ">=18"
50
52
  }
51
53
  }