@haraka/test-fixtures 0.0.0-stage → 2.0.1

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/logger.js ADDED
@@ -0,0 +1,125 @@
1
+ import util from 'node:util'
2
+
3
+ /**
4
+ * A log method; a recording stub() when makeConnection() gets stubLogs.
5
+ * @typedef {((...args: any[]) => any) & Partial<Pick<import('./stub.js').Stub, 'called' | 'callCount' | 'calls' | 'args'>>} LogMethod
6
+ */
7
+
8
+ const logger = {}
9
+
10
+ logger.levels = {
11
+ DATA: 9,
12
+ PROTOCOL: 8,
13
+ DEBUG: 7,
14
+ INFO: 6,
15
+ NOTICE: 5,
16
+ WARN: 4,
17
+ ERROR: 3,
18
+ CRIT: 2,
19
+ ALERT: 1,
20
+ EMERG: 0,
21
+ }
22
+
23
+ // Add LOG* aliases
24
+ for (const level in logger.levels) {
25
+ logger[`LOG${level}`] = logger.levels[level]
26
+ }
27
+
28
+ logger.formats = {
29
+ DEFAULT: 'DEFAULT',
30
+ LOGFMT: 'LOGFMT',
31
+ JSON: 'JSON',
32
+ }
33
+
34
+ logger.loglevel = logger.levels.WARN
35
+ logger.format = logger.formats.DEFAULT
36
+ logger.timestamps = false
37
+ logger.deferred_logs = []
38
+
39
+ logger.log = function (level, data) {
40
+ if (level === 'PROTOCOL') return
41
+ if (level === 'DEBUG') return
42
+ data = data.replace(/\r/g, '\\r').replace(/\n$/, '')
43
+
44
+ console.log(data)
45
+ return true
46
+ }
47
+
48
+ logger.set_loglevel = function (level) {
49
+ if (level === undefined || level === null) return
50
+
51
+ const loglevel_num = parseInt(level)
52
+ if (typeof level === 'string') {
53
+ logger.loglevel = logger.levels[level.toUpperCase()]
54
+ } else {
55
+ logger.loglevel = loglevel_num
56
+ }
57
+
58
+ if (!Number.isInteger(logger.loglevel)) {
59
+ logger.loglevel = logger.levels.WARN
60
+ }
61
+ }
62
+
63
+ logger.would_log = function (level) {
64
+ if (logger.loglevel < level) return false
65
+ return true
66
+ }
67
+
68
+ logger.set_format = function (format) {
69
+ if (format) {
70
+ logger.format = logger.formats[format.toUpperCase()]
71
+ }
72
+ if (!logger.format) {
73
+ logger.format = logger.formats.DEFAULT
74
+ }
75
+ }
76
+
77
+ logger.set_timestamps = function (value) {
78
+ logger.timestamps = !!value
79
+ }
80
+
81
+ logger.log_if_level = function (level, key, plugin) {
82
+ return function () {
83
+ if (logger.loglevel < logger[key]) return
84
+ const levelstr = `[${level}]`
85
+ let str = ''
86
+ const uuidstr = '[-]'
87
+ let pluginstr = `[${plugin || 'core'}]`
88
+ for (let i = 0; i < arguments.length; i++) {
89
+ const data = arguments[i]
90
+ if (typeof data !== 'object') {
91
+ str += data
92
+ continue
93
+ }
94
+ if (!data) continue
95
+ if (data.name) {
96
+ pluginstr = `[${data.name}]`
97
+ } else {
98
+ str += util.inspect(data)
99
+ }
100
+ }
101
+ logger.log(level, [levelstr, uuidstr, pluginstr, str].join(' '))
102
+ return true
103
+ }
104
+ }
105
+
106
+ logger.add_log_methods = function (object, plugin) {
107
+ if (!object) return
108
+ if (typeof object !== 'object') return
109
+ for (const level in logger.levels) {
110
+ const fname = `log${level.toLowerCase()}`
111
+ if (object[fname]) continue // already added
112
+ object[fname] = logger.log_if_level(level, `LOG${level}`, plugin)
113
+ }
114
+ }
115
+
116
+ logger.add_log_methods(logger, { name: 'test-fixture' })
117
+
118
+ /**
119
+ * @typedef {'DATA' | 'PROTOCOL' | 'DEBUG' | 'INFO' | 'NOTICE' | 'WARN' | 'ERROR' | 'CRIT' | 'ALERT' | 'EMERG'} Level
120
+ */
121
+ /** @type {typeof logger & { [L in Level as `LOG${L}`]: number } & { [L in Level as `log${Lowercase<L>}`]: LogMethod }} */
122
+ const typed = /** @type {any} */ (logger)
123
+
124
+ // haraka_require('logger') in legacy plugins gets the object, not a namespace
125
+ export { typed as default, typed as 'module.exports' }
package/lib/plugin.js ADDED
@@ -0,0 +1,313 @@
1
+ import fs from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import path from 'node:path'
4
+ import vm from 'node:vm'
5
+
6
+ import config from '@haraka/config'
7
+ import * as constants from '@haraka/constants'
8
+
9
+ import logger from './logger.js'
10
+
11
+ const require = createRequire(import.meta.url)
12
+
13
+ // Installed under a project's node_modules, plugins resolve from that project.
14
+ const NODE_MODULES = `${path.sep}node_modules${path.sep}`
15
+ const lib_dir = import.meta.dirname
16
+ const base_dir = lib_dir.includes(NODE_MODULES) ? lib_dir.slice(0, lib_dir.lastIndexOf(NODE_MODULES)) : lib_dir
17
+
18
+ const server = { notes: {} }
19
+
20
+ /** @typedef {Plugin & Record<string, any>} LoadedPlugin a Plugin with its module's exports */
21
+
22
+ class Plugin {
23
+ constructor(name) {
24
+ // strip the haraka-plugin- prefix for identity, as core Haraka does, so
25
+ // results land under the short name; path resolution keeps the full name
26
+ this.name = name.startsWith('haraka-plugin-') ? name.slice(14) : name
27
+ this.base = {}
28
+ this.timeout = 10
29
+ this.plugin_path = this._get_plugin_path(name)
30
+ this.config = this._get_config()
31
+ this.hooks = {}
32
+ this.last_err = ''
33
+
34
+ // Set in server.js; initialized to empty object
35
+ // to prevent it from blowing up any unit tests.
36
+ this.server = { notes: {} }
37
+
38
+ constants.import(global)
39
+
40
+ logger.add_log_methods(this, this.name)
41
+
42
+ this._compile()
43
+ }
44
+
45
+ register() {
46
+ // Plugin lifecycle hook - can be overridden via inherits()
47
+ }
48
+
49
+ haraka_require(name) {
50
+ return require(`./${name}`)
51
+ }
52
+
53
+ core_require(name) {
54
+ return this.haraka_require(name)
55
+ }
56
+
57
+ _has_package_json(candidate_path) {
58
+ if (/\/package\.json$/.test(candidate_path)) {
59
+ this.hasPackageJson = true
60
+ return
61
+ }
62
+
63
+ const enclosing_dir = path.dirname(candidate_path)
64
+ if (fileExists(path.join(enclosing_dir, 'package.json'))) {
65
+ this.hasPackageJson = true
66
+ return true
67
+ }
68
+ return false
69
+ }
70
+
71
+ _get_plugin_path(name) {
72
+ this.hasPackageJson = false
73
+ if (!name) name = this.name
74
+ const paths = []
75
+ if (base_dir === lib_dir) {
76
+ // for haraka-test-fixture tests
77
+ paths.push(
78
+ path.resolve(base_dir, '..', `${name}.js`),
79
+ path.resolve(base_dir, '..', name, 'package.json'),
80
+ path.resolve(base_dir, '..', 'test', 'fixtures', `${name}.js`),
81
+ path.resolve(base_dir, '..', 'test', 'fixtures', name, 'package.json'),
82
+ )
83
+ } else if ('plugins' == path.basename(base_dir)) {
84
+ // for 'inherits' in Haraka/tests/plugins/*.js
85
+ paths.push(path.resolve(base_dir, `${name}.js`), path.resolve(base_dir, name, 'package.json'))
86
+ } else {
87
+ if (dirExists(path.join(base_dir, 'plugins'))) {
88
+ // Haraka/plugins/*.js && Haraka/node_modules/*
89
+ paths.push(
90
+ path.resolve(base_dir, 'plugins', `${name}.js`),
91
+ path.resolve(base_dir, 'plugins', name, 'package.json'),
92
+ path.resolve(base_dir, 'node_modules', name, 'package.json'),
93
+ )
94
+ } else {
95
+ // npm packaged plugins
96
+ paths.push(
97
+ // npm packaged plugin inheriting an npm packaged plugin
98
+ path.resolve(base_dir, 'node_modules', name, 'package.json'),
99
+
100
+ path.resolve(base_dir, `${name}.js`),
101
+ path.resolve(base_dir, 'package.json'),
102
+ )
103
+ }
104
+ }
105
+ // console.log(paths);
106
+
107
+ for (let i = 0; i < paths.length; i++) {
108
+ try {
109
+ fs.statSync(paths[i])
110
+ this._has_package_json(paths[i])
111
+ return paths[i]
112
+ } catch (err) {
113
+ switch (err.code) {
114
+ case 'ENOENT':
115
+ break
116
+ default:
117
+ console.error(`Error checking for plugin ${name} at ${paths[i]}: ${err.message}`)
118
+ }
119
+ }
120
+ }
121
+ }
122
+
123
+ _get_config() {
124
+ if (this.hasPackageJson) {
125
+ // It's a package/folder plugin - look in plugin folder for defaults,
126
+ // haraka/config folder for overrides
127
+ return config.module_config(path.dirname(this.plugin_path), process.env.HARAKA || base_dir)
128
+ }
129
+
130
+ if (process.env.HARAKA) {
131
+ // Plain .js file, installed mode - look in core folder for defaults,
132
+ // install dir for overrides
133
+ return config.module_config(base_dir, process.env.HARAKA)
134
+ }
135
+
136
+ if (process.env.HARAKA_TEST_DIR) {
137
+ return config.module_config(process.env.HARAKA_TEST_DIR)
138
+ }
139
+
140
+ // Plain .js file, git mode - just look in this folder
141
+ return config.module_config(base_dir)
142
+ }
143
+
144
+ register_hook(hook_name, method_name, priority) {
145
+ priority = parseInt(priority)
146
+ if (!priority) priority = 0
147
+ if (priority > 100) priority = 100
148
+ if (priority < -100) priority = -100
149
+
150
+ this.hooks[hook_name] = this.hooks[hook_name] || []
151
+ this.hooks[hook_name].push(method_name)
152
+
153
+ this.loginfo(`registered hook ${hook_name} to ${this.name}.${method_name} priority ${priority}`)
154
+ }
155
+
156
+ _get_code(pi_path) {
157
+ if (this.hasPackageJson) return require_code(path.dirname(pi_path))
158
+
159
+ let source
160
+ try {
161
+ source = fs.readFileSync(pi_path, 'utf8')
162
+ } catch (err) {
163
+ throw `Loading plugin ${this.name} failed: ${err}`
164
+ }
165
+ if (is_module(source, pi_path)) {
166
+ this.isModule = true
167
+ return require_code(pi_path)
168
+ }
169
+ // a hashbang is only valid as the first line, and "use strict" goes there
170
+ return `"use strict";\n${source.replace(/^#!.*/, '')}`
171
+ }
172
+
173
+ inherits(parent_name) {
174
+ const parent_plugin = load_and_compile(parent_name)
175
+
176
+ // A core base plugin (e.g. 'auth/auth_base', 'queue/discard') is
177
+ // not resolvable from a standalone plugin's test environment;
178
+ // _get_plugin_path() then falls through to the current plugin's
179
+ // own package.json, so `parent_plugin` is really *this* plugin.
180
+ // Inheriting from ourselves and re-invoking register() recurses
181
+ // until the stack overflows. Treat an unresolved core base plugin
182
+ // as a no-op instead.
183
+ if (parent_plugin.plugin_path === this.plugin_path) {
184
+ this.logdebug(`inherits('${parent_name}') not resolvable in test fixtures; skipping`)
185
+ return
186
+ }
187
+
188
+ for (const method in parent_plugin) {
189
+ if (!this[method]) {
190
+ this[method] = parent_plugin[method]
191
+ }
192
+ }
193
+ if (parent_plugin.register) {
194
+ parent_plugin.register.call(this)
195
+ }
196
+ this.base[parent_name] = parent_plugin
197
+ }
198
+
199
+ _make_custom_require() {
200
+ return (module) => {
201
+ // module plugins see the globals a package plugin does
202
+ if (this.hasPackageJson || this.isModule) {
203
+ const mod = require(module)
204
+ constants.import(global)
205
+ global.server = server
206
+ return mod
207
+ }
208
+
209
+ if (module === './config') {
210
+ return this.config
211
+ }
212
+
213
+ if (!/^\./.test(module)) {
214
+ return require(module)
215
+ }
216
+
217
+ for (const ext of [`${module}.js`, module]) {
218
+ if (fs.existsSync(path.join(base_dir, ext))) {
219
+ return require(module)
220
+ }
221
+ }
222
+
223
+ return require(path.join(path.dirname(this.plugin_path), module))
224
+ }
225
+ }
226
+
227
+ _compile() {
228
+ const pp = this.plugin_path
229
+ if (!pp) throw 'could not find path to plugin'
230
+ const code = this._get_code(pp)
231
+ if (!code) return
232
+
233
+ const sandbox = {
234
+ require: this._make_custom_require(),
235
+ __filename: pp,
236
+ __dirname: path.dirname(pp),
237
+ exports: this,
238
+ console,
239
+ setTimeout,
240
+ clearTimeout,
241
+ setInterval,
242
+ clearInterval,
243
+ process,
244
+ Buffer,
245
+ Math,
246
+ server,
247
+ setImmediate,
248
+ }
249
+ if (this.hasPackageJson) {
250
+ delete sandbox.__filename
251
+ }
252
+ constants.import(sandbox)
253
+ runInSandbox(code, sandbox, this.plugin_path)
254
+ }
255
+ }
256
+
257
+ function runInSandbox(code, sandbox, filename) {
258
+ if (typeof vm.Script === 'function' && typeof vm.createContext === 'function') {
259
+ const context = vm.createContext(sandbox)
260
+ const script = new vm.Script(code, {
261
+ filename,
262
+ displayErrors: true,
263
+ })
264
+ return script.runInContext(context, { displayErrors: true })
265
+ }
266
+
267
+ // Backward-compat fallback for older runtimes.
268
+ return vm.runInNewContext(code, sandbox, filename)
269
+ }
270
+
271
+ function dirExists(dir) {
272
+ try {
273
+ if (fs.statSync(dir).isDirectory()) return true
274
+ } catch (ignore) {}
275
+ return false
276
+ }
277
+
278
+ function fileExists(filePath) {
279
+ try {
280
+ if (fs.statSync(filePath).isFile()) return true
281
+ } catch (ignore) {
282
+ // console.error(ignore);
283
+ }
284
+ return false
285
+ }
286
+
287
+ // require(esm) loads an ES module plugin synchronously, as a package plugin is
288
+ function require_code(target) {
289
+ return `const _p = require(${JSON.stringify(target)}); for (const k in _p) { exports[k] = _p[k] }`
290
+ }
291
+
292
+ // import/export can't compile as a script, which is how Node detects ES module syntax too
293
+ function is_module(code, filename) {
294
+ try {
295
+ new vm.Script(code, { filename })
296
+ return false
297
+ } catch (err) {
298
+ return err instanceof SyntaxError && /\b(import|export)\b/.test(err.message)
299
+ }
300
+ }
301
+
302
+ function load_and_compile(name) {
303
+ const plugin = new Plugin(name)
304
+ if (!plugin.plugin_path) {
305
+ throw `Loading plugin ${plugin.name} failed: No plugin with this name found`
306
+ }
307
+ return plugin
308
+ }
309
+
310
+ // `new` yields the plugin with its module's exports
311
+ const LoadablePlugin = /** @type {(new (name: string) => LoadedPlugin) & typeof Plugin} */ (Plugin)
312
+
313
+ export { LoadablePlugin as default, LoadablePlugin as 'module.exports' }
package/lib/stub.js ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @typedef {{
3
+ * (...args: any[]): any,
4
+ * called: boolean,
5
+ * callCount: number,
6
+ * calls: any[][],
7
+ * args: any[] | undefined,
8
+ * thisArg: any,
9
+ * reset(): void,
10
+ * }} Stub
11
+ */
12
+
13
+ /**
14
+ * Creates a stub function that records calls.
15
+ *
16
+ * Properties on the returned stub:
17
+ * .called {boolean} true after the first call
18
+ * .callCount {number} number of times called
19
+ * .calls {Array} each element is an Array of arguments from one call
20
+ * .args {Array} arguments from the most recent call (undefined if never called)
21
+ * .thisArg {*} `this` from the most recent call
22
+ * .reset() resets all tracking state
23
+ *
24
+ * @param {*} [returnValue] - value the stub returns when called
25
+ * @returns {Stub}
26
+ */
27
+ export function stub(returnValue) {
28
+ function stub(...args) {
29
+ stub.called = true
30
+ stub.callCount++
31
+ stub.calls.push(args)
32
+ stub.args = args
33
+ stub.thisArg = this
34
+ return returnValue
35
+ }
36
+
37
+ stub.reset = function () {
38
+ stub.called = false
39
+ stub.callCount = 0
40
+ stub.calls = []
41
+ stub.args = undefined
42
+ stub.thisArg = undefined
43
+ }
44
+
45
+ stub.reset()
46
+ return stub
47
+ }
48
+
49
+ // the older `fixtures.stub.stub()` form
50
+ stub.stub = stub