@irrelon/emitter 6.0.0 → 6.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.
@@ -4,20 +4,20 @@ import { Emitter, EmitterEventsInterface, EventListenerCallback, ListenerReturnF
4
4
  let expectedAssertions = 0;
5
5
  let actualAssertions = 0;
6
6
 
7
- function expect (val: number) {
7
+ function expect(val: number) {
8
8
  expectedAssertions = val;
9
9
  }
10
10
 
11
- function reset () {
11
+ function reset() {
12
12
  expectedAssertions = 0;
13
13
  actualAssertions = 0;
14
14
  }
15
15
 
16
- function countAssertion () {
16
+ function countAssertion() {
17
17
  actualAssertions++;
18
18
  }
19
19
 
20
- function check () {
20
+ function check() {
21
21
  if (expectedAssertions === undefined || expectedAssertions === actualAssertions) {
22
22
  return;
23
23
  }
@@ -53,13 +53,13 @@ describe("Emitter", () => {
53
53
 
54
54
  // Test extending Emitter and modifying base functionality
55
55
  class MyClass extends Emitter {
56
- testFunc () {
56
+ testFunc() {
57
57
  testFuncCount++;
58
58
  }
59
59
 
60
60
  on(eventName: string, id: string, listener: EventListenerCallback): this;
61
61
  on(eventName: string, listener: EventListenerCallback): this;
62
- on (eventName: string, ...rest: any[]): this {
62
+ on(eventName: string, ...rest: any[]): this {
63
63
  const restTypes = rest.map((arg) => typeof arg);
64
64
 
65
65
  if (restTypes[0] === "function") {
@@ -73,14 +73,14 @@ describe("Emitter", () => {
73
73
  }
74
74
 
75
75
  // @ts-ignore
76
- emit (eventName: string, ...rest: any[]) {
76
+ emit(eventName: string, ...rest: any[]) {
77
77
  return super.emitId(eventName, "^^noId", ...rest);
78
78
  }
79
79
 
80
80
  off(eventName: string, id: string, listener?: EventListenerCallback): this;
81
81
  off(eventName: string, listener?: EventListenerCallback): this;
82
82
  off(eventName: string): this;
83
- off (eventName: string, ...rest: any[]) {
83
+ off(eventName: string, ...rest: any[]) {
84
84
  let id = rest[0];
85
85
  let func = rest[1];
86
86
 
@@ -263,6 +263,39 @@ describe("Emitter", () => {
263
263
  assert.strictEqual(results[1], "Foo2 Return Value", "Return data for foo2 was not correct");
264
264
  });
265
265
 
266
+ it("Supports awaiting async and non-async rpc listener return data", async () => {
267
+ interface MyTestEvents {
268
+ foo1: () => string | Promise<string>;
269
+ foo2: () => string;
270
+ }
271
+
272
+ const emitter = new Emitter<EmitterEventsInterface<MyTestEvents>>();
273
+ let listenerFiredCount = 0;
274
+
275
+ emitter.on("foo1", () => {
276
+ return new Promise<string>((resolve) => {
277
+ setTimeout(() => {
278
+ listenerFiredCount++;
279
+ resolve("Foo1 Return Value");
280
+ }, 1000);
281
+ });
282
+ });
283
+
284
+ emitter.on("foo2", () => {
285
+ return "Foo2 Return Value";
286
+ });
287
+
288
+ const time = new Date().getTime();
289
+ const result1 = await emitter.rpc("foo1");
290
+ const result2 = emitter.rpc("foo2");
291
+ const delta = new Date().getTime() - time;
292
+
293
+ assert.ok(delta > 900, "Delta was not correct, await may not have paused?");
294
+ assert.ok(listenerFiredCount === 1, "listenerFiredCount was not correct, await may not have been used?");
295
+ assert.strictEqual(result1, "Foo1 Return Value", "Return data for foo1 was not correct");
296
+ assert.strictEqual(result2, "Foo2 Return Value", "Return data for foo2 was not correct");
297
+ });
298
+
266
299
  it("Supports responding with a cancellation signal", async () => {
267
300
  interface MyTestEvents {
268
301
  foo: () => string | ListenerReturnFlag;
@@ -566,4 +599,4 @@ describe("Emitter", () => {
566
599
  );
567
600
  });
568
601
  });
569
- });
602
+ });
package/fixPaths.cjs DELETED
@@ -1,183 +0,0 @@
1
- /**
2
- * A very basic search and replace function to find import and export statements
3
- * in .js files where the path of the file being specified does not have a .js
4
- * extension and replace those paths with one that has a .js extension.
5
- *
6
- * This would be much better written using abstract source trees to do the
7
- * re-writing which would be "safer", however this is a fully working function
8
- * and doesn't seem to mess anything up at present.
9
- */
10
- const chokidar = require("chokidar");
11
- const fs = require("fs");
12
- const { readFile, writeFile, readdir } = require("fs").promises;
13
- const { resolve } = require("path");
14
- const { minimatch } = require("minimatch");
15
-
16
- const matchPattern = ["**/*.js", "**/*.jsx"];
17
- const excludePattern = ["node_modules", "react", ".git"];
18
-
19
- const expressions = [{
20
- exp: /import(.*)?["']([.]+)(((?!\.js).)*?)["'];/g,
21
- update: (match, isIndex) => {
22
- if (isIndex) {
23
- return `import${match[1]}"${match[2]}${match[3]}/index.js";`;
24
- }
25
-
26
- return `import${match[1]}"${match[2]}${match[3]}.js";`;
27
- }
28
- }, {
29
- exp: /export\s(.*)?\sfrom\s["']([.]+)(((?!\.js).)*?)["'];/g,
30
- update: (match, isIndex) => {
31
- if (isIndex) {
32
- return `export ${match[1]} from "${match[2]}${match[3]}/index.js";`;
33
- }
34
-
35
- return `export ${match[1]} from "${match[2]}${match[3]}.js";`;
36
- }
37
- }];
38
-
39
- let tsPaths = {};
40
- let tsResolvedPaths = {};
41
-
42
- const readTsConfig = () => {
43
- const config = require("./tsconfig.json");
44
- tsPaths = config.compilerOptions.paths;
45
-
46
- Object.entries(tsPaths).forEach(([key, replacementArr]) => {
47
- tsResolvedPaths[key] = replacementArr.map((dir) => {
48
- return resolve(__dirname, dir);
49
- });
50
- });
51
- };
52
-
53
- async function getFiles (dir, gitIgnoreArr) {
54
- const dirArr = await readdir(dir, { withFileTypes: true });
55
-
56
- const finalList = dirArr.filter((filePath) => {
57
- return excludePattern.every((glob) => !minimatch(filePath.name, glob));
58
- });
59
-
60
- const files = await Promise.all(finalList.map((tmpDir) => {
61
- const res = resolve(dir, tmpDir.name);
62
- return tmpDir.isDirectory() ? getFiles(res) : [res];
63
- })).then((results) => {
64
- return results.reduce((arr, item) => {
65
- arr.push(...item);
66
- return arr;
67
- }, []);
68
- });
69
-
70
- const finalFiles = files.filter((file) => {
71
- if (!file || !file.trim()) return false;
72
- return matchPattern.some((glob) => minimatch(file, glob));
73
- });
74
-
75
- return Array.prototype.concat(...finalFiles);
76
- }
77
-
78
- const processMatches = (regExp, fileFolder, content, updateFunc) => {
79
- let match;
80
- while (match = regExp.exec(content)) {
81
- const pathToItemFile = resolve(fileFolder, match[2] + match[3] + ".js");
82
- const pathToItemFolderIndexFile = resolve(fileFolder, match[2] + match[3] + "/index.js");
83
- let pathStatFile;
84
- let pathStatFolderIndexFile;
85
-
86
- try {
87
- pathStatFile = fs.lstatSync(pathToItemFile);
88
- } catch (err) {
89
- pathStatFolderIndexFile = undefined;
90
- }
91
-
92
- try {
93
- pathStatFolderIndexFile = fs.lstatSync(pathToItemFolderIndexFile);
94
- } catch (err) {
95
- pathStatFolderIndexFile = undefined;
96
- }
97
-
98
- if (pathStatFile) {
99
- // Just add .js to the end of the path
100
- content = content.replace(match[0], updateFunc(match, false));
101
- } else if (pathStatFolderIndexFile) {
102
- content = content.replace(match[0], updateFunc(match, true));
103
- }
104
- }
105
-
106
- return content;
107
- };
108
-
109
- const processFile = (file) => {
110
- if (!file) return;
111
-
112
- //console.log(`Processing ${file}...`);
113
-
114
- readFile(file).then((fileContentsBuffer) => {
115
- const fileFolderArr = file.split("/");
116
- fileFolderArr.pop();
117
-
118
- const fileFolder = fileFolderArr.join("/");
119
-
120
- const fileContent = fileContentsBuffer.toString();
121
- let updatedContent = fileContent;
122
-
123
- Object.entries(tsPaths).forEach(([key, replacementArr]) => {
124
- const find = key.replace("*", "");
125
- const replace = replacementArr[0].replace("*", "");
126
-
127
- const relativeSteps = new Array(file.replace(__dirname, "").split("/").length - 2).fill("../").join("");
128
- const replacementPath = relativeSteps + replace;
129
-
130
- updatedContent = updatedContent.replaceAll(find, replacementPath);
131
- });
132
-
133
- expressions.forEach((expression) => {
134
- updatedContent = processMatches(expression.exp, fileFolder, updatedContent, expression.update);
135
- expression.exp.lastIndex = 0;
136
- })
137
-
138
- if (fileContent === updatedContent) {
139
- //console.log(`No change ${file}`);
140
- return;
141
- }
142
-
143
- writeFile(file, updatedContent).then(() => {
144
- console.log(`Updated ${file}`);
145
- });
146
- });
147
- };
148
-
149
- const runSearchReplace = () => {
150
- // Scan all folders
151
- readFile(resolve(__dirname, ".gitignore")).then((result) => {
152
- return result.toString().split("\n").filter((line) => {
153
- return !line.startsWith("#");
154
- }).filter((line) => {
155
- return Boolean(line.trim());
156
- });
157
- }).then((gitIgnoreArr) => {
158
- return getFiles(__dirname, gitIgnoreArr);
159
- }).then((files) => {
160
- // Now scan the files for matching regular expressions
161
- // of imports without extensions
162
- files.forEach((file) => {
163
- processFile(file);
164
- });
165
-
166
- console.log(`Processed ${files.length} files`);
167
- });
168
- };
169
-
170
- readTsConfig();
171
- runSearchReplace();
172
-
173
- const watcher = chokidar.watch(__dirname, { persistent: true });
174
-
175
- watcher.on("change", (filename) => {
176
- if (filename.indexOf("tsconfig.json") > -1) {
177
- console.log("Updating tsconfig.json data");
178
- readTsConfig();
179
- }
180
- if (!matchPattern.some((glob) => minimatch(filename, glob))) return;
181
- //console.log("Changed", filename);
182
- processFile(filename);
183
- });